
# set file location here:
dir1 <- "D:\\Research\\Media\\Ad Primaries\\rep\\"

# location of the dll file for complied c++ code
fastr_dll_loc <- paste(dir1,"fastr.dll",sep="")

# load an r library, downloading if necesary
library0 <- function(s)
{
	if(s %in% rownames(installed.packages()) == FALSE) {install.packages(s,repos='http://cran.us.r-project.org')}
	require(s,character.only=TRUE)
}

library0("readxl")
library0("stringr")
library0("fastmatch")
library0("lfe")
library0("numDeriv") # for numerical derivatives
library0("data.table") # for month

# uncomment below to log output rather than print to console
# sink(paste(dir1,"log.txt",sep=""))

# load the ad data
ads2000  <- read_excel(paste(dir1,"adcounts.xlsx",sep=""),sheet="ads2000")
ads2004  <- read_excel(paste(dir1,"adcounts.xlsx",sep=""),sheet="ads2004")
ads2008  <- read_excel(paste(dir1,"adcounts.xlsx",sep=""),sheet="ads2008")
ads2012  <- read_excel(paste(dir1,"adcounts.xlsx",sep=""),sheet="ads2012")
ads2016  <- read_excel(paste(dir1,"adcounts.xlsx",sep=""),sheet="ads2016")

df <- readRDS(file=paste(dir1,"primary.Rda",sep=""))

therm <- df$therm
partymatch <- df$partymatch
respid <- df$respid
candid <- df$candid
candparty <- df$candparty
primdist <- df$primdist
primint <- df$primint
primintchoice <- df$primintchoice
year <- df$year
source <- df$source
date <- df$date
state <- df$state
dma <- df$dma
prob <- df$prob
prob_cont <- df$prob_cont
poll_cont <- df$poll_cont
bin <- 1 *(therm > .5)
bin[therm==.5] <- NA
grp_4wk_p <- df$grp_4wk_p
grp_4wk_pa <- df$grp_4wk_pa
grp_4wk_pc <- df$grp_4wk_pc
grp_4wk_aa <- df$grp_4wk_aa
grp_4wk_ac <- df$grp_4wk_ac
num_4wk_p <- df$num_4wk_p
num_4wk_pa <- df$num_4wk_pa
num_4wk_pc <- df$num_4wk_pc
num_4wk_aa <- df$num_4wk_aa
num_4wk_ac <- df$num_4wk_ac
grp_2wk_p <- df$grp_2wk_p
grp_2wk_pa <- df$grp_2wk_pa
grp_2wk_pc <- df$grp_2wk_pc
grp_2wk_aa <- df$grp_2wk_aa
grp_2wk_ac <- df$grp_2wk_ac
grp_8wk_p <- df$grp_8wk_p
grp_8wk_pa <- df$grp_8wk_pa
grp_8wk_pc <- df$grp_8wk_pc
grp_8wk_aa <- df$grp_8wk_aa
grp_8wk_ac <- df$grp_8wk_ac
n <- nrow(df)

#sampfav <- !is.na(therm) & !is.na(partymatch) & !is.na(pro) & !is.na(runanti) & !is.na(anti) & (candparty=="D"|candparty=="R")
#sampint <- !is.na(primint) & !is.na(partymatch) & !is.na(pro) & !is.na(runanti) & !is.na(anti) & (candparty=="D"|candparty=="R")
#sampprob <- !is.na(prob) & !is.na(partymatch) & !is.na(pro) & !is.na(runanti) & !is.na(anti) & (candparty=="D"|candparty=="R")

#df2 <- data.frame(therm=therm,partymatch=partymatch,respid=respid,candid=candid,candparty=candparty,primdist=primdist,primint=primint,primintchoice=primintchoice,year=year,source=source,date=date,state=state,dma=dma,prob=prob,prob_cont=prob_cont,poll_cont=poll_cont,grp_4wk_p=grp_4wk_p,grp_4wk_pa=grp_4wk_pa,grp_4wk_pc=grp_4wk_pc,grp_4wk_aa=grp_4wk_aa,grp_4wk_ac=grp_4wk_ac,num_4wk_p=num_4wk_p,num_4wk_pa=num_4wk_pa,num_4wk_pc=num_4wk_pc,num_4wk_aa=num_4wk_aa,num_4wk_ac=num_4wk_ac,grp_2wk_p=grp_2wk_p,grp_2wk_pa=grp_2wk_pa,grp_2wk_pc=grp_2wk_pc,grp_2wk_aa=grp_2wk_aa,grp_2wk_ac=grp_2wk_ac,grp_8wk_p=grp_8wk_p,grp_8wk_pa=grp_8wk_pa,grp_8wk_pc=grp_8wk_pc,grp_8wk_aa=grp_8wk_aa,grp_8wk_ac=grp_8wk_ac)
#df3 <- df2[sampfav|sampint|sampprob,]
#saveRDS(df3,file=paste(dir1,"primary3.Rda",sep=""))

effect_lim <- function(Theta,fac,opt=1)
{
	if(opt == 1) {
		Theta[1] / (Theta[2] - fac * Theta[3])
	} else if(opt == 2) {
		Theta[1] / (Theta[2] - fac * Theta[4])
	} else if(opt == 3) {
		Theta[1] / (Theta[3] - fac * Theta[5])
	} else {
		Theta[1] / (Theta[2] - fac * Theta[4]) - Theta[1] / (Theta[3] - fac * Theta[5])
	}
}

effect_cross <- function(Theta,opt=1)
{
	if(opt == 1) {
		Theta[3] / Theta[2]
	} else if(opt == 2) {
		Theta[4] / Theta[2]
	} else if(opt == 3) {
		Theta[5] / Theta[3]
	} else {
		Theta[4] / Theta[2] - Theta[5] / Theta[3]
	}
}

get_coef1 <- function(model1,alpha,fac,opt=1)
{
	if(opt == 1 | opt == 2) {
		dm1 <- delta.method(effect_lim,model1$theta,model1$V,fac=fac)
	} else if(opt == 3) {
		dm1 <- delta.method(effect_lim,model1$theta,model1$V,fac=fac,opt=2)
	} else if(opt == 4) {
		dm1 <- delta.method(effect_lim,model1$theta,model1$V,fac=fac,opt=3)
	} else {
		dm1 <- delta.method(effect_lim,model1$theta,model1$V,fac=fac,opt=4)
	}

	ret <- c(NA,NA)
	ret[1] <- dig3(dm1$est)
	if(opt == 1) {
		if(2 * dnorm((dm1$est - 1) / dm1$se) < alpha) ret[1] <- paste(ret[1],"$\\dagger$",sep="")
		ret[2] <- as.se(dm1$se)
	} else if(opt == 4) {
		if(2 * dnorm((dm1$est) / dm1$se) < alpha) ret[1] <- paste(ret[1],"*",sep="")
		ret[2] <- dm1$se
	} else {
		if(2 * dnorm((dm1$est - 1) / dm1$se) < alpha) ret[1] <- paste(ret[1],"^",sep="")
		ret[2] <- dm1$se
	}
	ret
}

get_coef2 <- function(model1,alpha,opt=1)
{
	if(opt == 1 | opt == 2) {
		dm1 <- delta.method(effect_cross,model1$theta,model1$V)
	} else if(opt == 3) {
		dm1 <- delta.method(effect_cross,model1$theta,model1$V,opt=2)
	} else if(opt == 4) {
		dm1 <- delta.method(effect_cross,model1$theta,model1$V,opt=3)
	} else {
		dm1 <- delta.method(effect_cross,model1$theta,model1$V,opt=4)
	}
	ret <- c(NA,NA)
	ret[1] <- dig3(dm1$est)
	if(2 * dnorm((dm1$est) / dm1$se) < alpha) ret[1] <- paste(ret[1],"*",sep="")
	if(opt == 1) {
		if(2 * dnorm((dm1$est - 1) / dm1$se) < alpha) ret[1] <- paste(ret[1],"$\\dagger$",sep="")
		ret[2] <- as.se(dm1$se)
	} else if(opt != 4) {
		if(2 * dnorm((dm1$est - 1) / dm1$se) < alpha) ret[1] <- paste(ret[1],"^",sep="")
		ret[2] <- dm1$se
	}
	ret
}

fix.mnl <- function(x)
{
	if(length(x$coef) == 3) {
		temp1 <- get_coef1(x,.1,0,opt=2)
		temp2 <- get_coef1(x,.1,.5,opt=2)
		temp3 <- get_coef1(x,.1,1,opt=2)
		temp4 <- get_coef2(x,.1,opt=2)
		x$stats$"Rel. Eff. at 0" <- temp1
		x$stats$"Rel. Eff. at 1/2" <- temp2
		x$stats$"Rel. Eff. at 1" <- temp3
		x$stats$"Crossover" <- temp4
	} else {
		temp1 <- get_coef1(x,.1,0,opt=3)
		temp2 <- get_coef1(x,.1,.5,opt=3)
		temp3 <- get_coef1(x,.1,1,opt=3)
		temp4 <- get_coef2(x,.1,opt=3)
		temp5 <- get_coef1(x,.1,0,opt=4)
		temp6 <- get_coef1(x,.1,.5,opt=4)
		temp7 <- get_coef1(x,.1,1,opt=4)
		temp8 <- get_coef2(x,.1,opt=4)
		temp9 <- get_coef1(x,.1,0,opt=5)
		temp10 <- get_coef1(x,.1,.5,opt=5)
		temp11 <- get_coef1(x,.1,1,opt=5)
		temp12 <- get_coef2(x,.1,opt=5)
		x$stats$"Con. Rel. Eff. at 0" <- temp1
		x$stats$"Con. Rel. Eff. at 1/2" <- temp2
		x$stats$"Con. Rel. Eff. at 1" <- temp3
		x$stats$"Con. Crossover" <- temp4
		x$stats$"Att. Rel. Eff. at 0" <- temp5
		x$stats$"Att. Rel. Eff. at 1/2" <- temp6
		x$stats$"Att. Rel. Eff. at 1" <- temp7
		x$stats$"Att. Crossover" <- temp8
		x$stats$"Con. - Att. Rel. Eff. at 0" <- temp9
		x$stats$"Con. - Att. Rel. Eff. at 1/2" <- temp10
		x$stats$"Con. - Att. Rel. Eff. at 1" <- temp11
		x$stats$"Con. - Att. Crossover" <- temp12
	}
	x
}

# stats to save, default
stats1 <- c("N","Rel. Eff. at 0","Rel. Eff. at 1/2","Rel. Eff. at 1","Crossover")

# formula, default
f1 <- therm ~ partymatch + pro + runanti + anti | respid + candid | 0 | respid

dig <- function(x,k=3)
{
	y <- format(round(x,k),nsmall=k,trim=T,scientific=F)
	for(i in 1:length(y)) {
		if(is.na(x[i])) y[i] <- ""
	}
	y
}

dig0 <- function(x)
{
	dig(x,0)
}

dig1 <- function(x)
{
	dig(x,1)
}

dig2 <- function(x)
{
	dig(x,2)
}

dig3 <- function(x)
{
	dig(x,3)
}

drop.na <- function(x) { x[!is.na(x)] }

rowMins <- function(x,na.rm=TRUE) { apply(x, 1, FUN=min, na.rm=na.rm) }
rowMaxs <- function(x,na.rm=TRUE) { apply(x, 1, FUN=max, na.rm=na.rm) }
colMins <- function(x,na.rm=TRUE) { apply(x, 2, FUN=min, na.rm=na.rm) }
colMaxs <- function(x,na.rm=TRUE) { apply(x, 2, FUN=max, na.rm=na.rm) }

apply0 <- function(func1,x,subset=numeric(0),by=numeric(0),bys=numeric(0),w=logical(0),...)
{
	n <- length(x)
	if(length(subset) != 0 & length(subset) != n) stop("error in apply0 -- incompadible dimensions (subset)")
	if(length(by) != 0 & length(by) != n) stop("error in apply0 -- incompadible dimensions (by)")
	if(length(w) != 0 & length(w) != n) stop("error in apply0 -- incompadible dimensions (w)")

	if(length(subset) == 0) {
		subset1 <- rep(TRUE,n)
	} else {
		subset1 <- subset
	}
	subset1 <- subset1 & !is.na(x)
	if(length(w) != 0) subset1 <- subset1 & !is.na(w)
	subset1[is.na(subset1)] <- FALSE
	if(length(by) != 0) by1 <- subset(by,subset1)
	x1 <- x[subset1]
	if(length(w) != 0) w1 <- w[subset1]
	if(length(x1) == 0) {
		NA
	} else {
		if(length(by) == 0) {
			if(length(w) == 0) {
				func1(x1,...)
			} else {
				func1(x1,w=w1,...)
			}
		} else {
			if(length(bys) == 0) bys <- sort(unique(by1))
		
			# if only one bys is left over, prevent error
			if(length(bys) == 1) {
				if(length(w) == 0) {
					return(func1(x1,...))
				} else {
					return(func1(x1,w=w1,...))
				}
			}
			
			# there has to be a better way than this...
			if(length(w) == 0) {
				dat1 <- cbind(x1,by1)[order(by1),]
			} else {
				dat1 <- cbind(x1,w1,by1)[order(by1),]
			}

			J <- length(unique(by1))
			start <- rep(NA,J)
			start[1] <- 1
			tab1 <- table(by1)

			if(J > 1) {
				for(j in 2:J) start[j] <- start[j-1] + tab1[j-1]
				end <- c(start[2:J]-1,sum(tab1))
			} else {
				end <- sum(tab1)
			}

			ret <- rep(NA,length(bys))
			if(length(w) == 0) {
				for(j in 1:J) {
					k <- fmatch(dat1[start[j],2],bys)
					if(!is.na(k)) ret[k] <- func1(as.numeric(dat1[start[j]:end[j],1]),...)
				}
			} else {
				for(j in 1:J) {
					k <- fmatch(dat1[start[j],2],bys)
					if(!is.na(k)) ret[k] <- func1(as.numeric(dat1[start[j]:end[j],1]),...,w=as.numeric(dat1[start[j]:end[j],2]))
				}
			}
			names(ret) <- bys
			ret
		}
	}
}


sum0 <- function(x,subset=numeric(0),by=numeric(0),bys=numeric(0))
{
	apply0(sum,x,subset,by,bys)
}

min0 <- function(x,subset=numeric(0),by=numeric(0),bys=numeric(0))
{
	apply0(min,x,subset,by,bys)
}

max0 <- function(x,subset=numeric(0),by=numeric(0),bys=numeric(0))
{
	apply0(max,x,subset,by,bys)
}

mean0 <- function(x,w=numeric(0),subset=numeric(0),by=numeric(0),bys=numeric(0),se=FALSE,ci=FALSE)
{
	n <- length(x)
	if(length(subset) != 0 & length(subset) != n) stop("error in mean0 -- incompadible dimensions (subset)")
	if(length(w) != 0 & length(w) != n) stop("error in mean0 -- incompadible dimensions (w)")
	if(!se & !ci) {
		if(length(w) == 0) {
			apply0(mean,x,subset,by,bys)
		} else {
			if(length(subset) == 0) {
				subset1 <- !is.na(x) & !is.na(w)
			} else {
				subset1 <- !is.na(x) & !is.na(w) & subset
			}
			apply0(mean,w*x,subset1,by,bys) / apply0(mean,w,subset1,by,bys)
		}
	} else {
		ret <- list()
		if(length(w) == 0) {
			ret$est <- apply0(mean,x,subset,by,bys)
			se1 <- ret$se <- (var0(x,subset,by,bys) / n0(x,subset,by,bys))^.5
		} else {
			if(length(subset) == 0) {
				subset1 <- !is.na(x) & !is.na(w)
			} else {
				subset1 <- !is.na(x) & !is.na(w) & subset
			}
			W = apply0(sum,w,subset1,by,bys)
			ret <- list()
			ret$est <- apply0(sum,w*x,subset1,by,bys) / W 
			se1 <- (var0(w*x,subset1,by,bys) * n0(w*x,subset1,by,bys) / W^2)^.5
		}
		if(se) ret$se <- se1
		if(ci) ret$ci <- c(ret$est - 1.96 * se1,ret$est + 1.96 * se1)
		ret
	}
}

str_split_vec <- function(x,sep)
{
	temp <- str_split(x,sep)
	n <- length(temp)
	m <- length(temp[[1]])
	res <- matrix(rep(NA,n*m),ncol=m)
	for(i in 1:n)
	{
		if(length(temp[[i]]) != m) stop("error in str_split_vec -- columns are not equal size")
		for(j in 1:m) res[i,j] <- temp[[i]][j]
	}	
	res
}

# table, w/ subset option
table0 <- function(x,subset=numeric(0),w=numeric(0),cats=numeric(0))
{
	n <- length(x)
	if(length(subset) != 0 & length(subset) != n) stop("error in table0 -- incompadible dimensions")
	if(length(w)      != 0 & length(w)      != n) stop("error in table0 -- incompadible dimensions")
	
	if(length(cats) == 0) {
		if(length(w) == 0) {
			if(length(subset) == 0) {
				subset1 <- subset(x,!is.na(x))
			} else {
				subset1 <- subset(x,subset&!is.na(x))
			}
			if(length(subset1) == 0) {
				NA
			} else {
				table(subset1)
			}
		} else {
			if(length(subset) == 0) {
				subset1 <- subset(x,!is.na(x)&!is.na(w))
				w1 <- subset(w,!is.na(x)&!is.na(w))
			} else {
				subset1 <- subset(x,subset&!is.na(x)&!is.na(w))
				w1 <- subset(w,subset&!is.na(x)&!is.na(w))
			}
			if(length(subset1) == 0) {
				NA
			} else {
				length(subset1) * wpct(subset1,w=w1)
			}
		}
	} else {
		if(length(w) == 0) w <- rep(1,n)
		if(length(subset) == 0) {
			subset1 <- subset(x,!is.na(x)&!is.na(w))
			w1 <- subset(w,!is.na(x)&!is.na(w))
		} else {
			subset1 <- subset(x,subset&!is.na(x)&!is.na(w))
			w1 <- subset(w,subset&!is.na(x)&!is.na(w))
		}
		tab1 <- length(subset1) * wpct(subset1,w=w1)
		m <- length(cats)
		tab2 <- rep(NA,m)
		tab2 <- tab1[fmatch(cats,names(tab1))]
		tab2
	}
}

fix.felm <- function(lm1,r.squared=F)
{
	lm1$ivs <- rownames(lm1$coef)
	lm1$theta <- as.vector(lm1$coef)
	lm1$se <- as.vector(lm1$se)
	lm1$stats <- list()
	lm1$stats$N <- lm1$N
	lm1$stats$C <- as.integer(lm1$p)
	if(r.squared) {
		lm1$stats$r.squared <- summary(lm1)$r.squared
	}
	lm1$V <- lm1$vcv
	lm1
}

output.models <- function(ms,stats=logical(0),rename=logical(0),statse=F)
{
	J <- length(ms)

	# rename ivs and stats
	if(length(rename) > 0) {
		for(j in 1:J) {
			for(k in 1:length(rename)) {
				# ivs
				idx <- fmatch(names(rename)[k],ms[[j]]$ivs)
				if(!is.na(idx)) ms[[j]]$ivs[idx] <- rename[[k]]

				# stats
				idx <- fmatch(names(rename)[k],names(ms[[j]]))
				if(!is.na(idx)) names(ms[[j]])[idx] <- rename[[k]]

				if(length(stats) > 0) {
					idx <- fmatch(names(rename)[k],stats)
					if(!is.na(idx)) stats[idx] <- rename[[k]]
				}
			}
		}
	}

	ivs <- ms[[1]]$ivs
	if(J > 1) for(j in 2:J) ivs <- c(ivs,ms[[j]]$ivs)
	ivs <- unique(ivs)

	# reorder ivs
	if(length(rename) > 0) {
		newnames <- as.vector(rename)
		newnames <- intersect(newnames,ivs)
		oldnames <- setdiff(ivs,newnames)
		ivs <- c(newnames,oldnames)
	}

	K <- length(ivs)
	coef <- matrix(rep(NA,J*K),ncol=J)
	se <- matrix(rep(NA,J*K),ncol=J)

	stats1 <- logical(0)
	for(j in 1:J) {
		if(length(stats) > 0) {
			idx <- drop.na(fmatch(stats,names(ms[[j]]$stats)))
			stats1 <- c(stats1,names(ms[[j]]$stats)[idx])
		} else {
			stats1 <- c(stats1,names(ms[[j]]$stats))
		}
		stats1 <- unique(stats1)
		#stats1 <- stats[!is.na(fmatch(stats,stats1))]
		extra <- list()
		if(statse) extrase <- list()
	}
	
	sum1 <- 0
	lenstats <- rep(NA,length(stats1))
	if(length(stats1) > 0) {
		for(i in 1:length(stats1)) {
			lenstats[i] <- NA
			for(j in 1:J) {
				idx <- fmatch(stats1[i],names(ms[[j]]$stats))
				if(!is.na(idx)) {
					if(is.na(lenstats[i])) {
						lenstats[i] <- length(ms[[j]]$stats[[idx]])
					} else if(lenstats[i] != length(ms[[j]]$stats[[idx]])) {
						stop("error in output.models -- incompadible dimensions in stats")
					}
				}
			}
			if(!statse) {
				sum1 <- sum1 + lenstats[i]
			} else {
				if(lenstats[i] != 1 && lenstats[i] != 2) stop("error -- invalid length for lenstats")
				sum1 <- sum1 + 1
			}
		}
	}

	for(j in 1:J)
	{
		for(k in 1:length(ms[[j]]$ivs))
		{
			coef[fmatch(ms[[j]]$ivs[k],ivs),j] <- ms[[j]]$theta[k]
			se[fmatch(ms[[j]]$ivs[k],ivs),j] <- ms[[j]]$se[k]
		}
	}

	if(length(stats1) > 0) {
		curr <- 1
		for(i in 1:length(stats1)) {
			if(!statse) {
				for(k in 1:lenstats[i]) {
					temp <- logical(0)
					for(j in 1:J) {
						idx <- fmatch(stats1[i],names(ms[[j]]$stats))
						if(!is.na(idx)) {
							temp <- c(temp,ms[[j]]$stats[[idx]][k])
						} else {
							temp <- c(temp,NA)
						}
					}
					extra[[curr]] <- temp
					curr <- curr + 1
				}
			} else {
				temp <- logical(0)
				temp2 <- logical(0)
				for(j in 1:J) {
					idx <- fmatch(stats1[i],names(ms[[j]]$stats))
					if(!is.na(idx)) {
						temp <- c(temp,ms[[j]]$stats[[idx]][1])
					} else {
						temp <- c(temp,NA)
					}
					extra[[i]] <- temp

					if(lenstats[i] == 2 & !is.na(idx)) {
						temp2 <- c(temp2,ms[[j]]$stats[[idx]][2])
					} else {
						temp2 <- c(temp2,NA)
					}
					extrase[[i]] <- temp2
				}	
			}
			
		}
	}

	rownames(coef) <- ivs
	colnames(coef) <- names(ms)
	rownames(se) <- ivs
	colnames(se) <- names(ms)
	if(length(stats1) > 0) {
		if(!statse) {
			statnames <- logical(0)
			for(i in 1:length(stats1)) {
				if(lenstats[i] == 1) {
					statnames <- c(statnames,stats1[i])
				} else {
					statnames <- c(statnames,paste(stats1[i],"[",1:lenstats[i],"]",sep=""))
				}
			}
			names(extra) <- statnames
			list(coef=coef,se=se,stats=extra)
		} else {
			names(extra) <- stats1
			names(extrase) <- stats1		
			list(coef=coef,se=se,stats=extra,statsse=extrase)		
		}
	} else {
		list(coef=coef,se=se)
	}
}

relabel.output <- function(o,oldivs=logical(0),newivs=logical(0),oldstats=logical(0),newstats=logical(0))
{
	J <- length(oldivs)
	if(length(newivs) != J) stop("error in relabel.output -- length(oldivs) != length(newivs)")
	if(J > 0) {
		for(j in 1:J) {
			idx <- fmatch(oldivs[j],rownames(o$coef))
			if(is.na(idx)) stop(paste("error in relabel.output -- oldiv not found in coef\noldiv: ",oldivs[j],sep=""))
			rownames(o$coef)[idx] <- newivs[j]
			idx <- fmatch(oldivs[j],rownames(o$se))
			if(is.na(idx)) stop("error in relabel.output -- oldiv not found in se")
			rownames(o$se)[idx] <- newivs[j]
		}
	}
	J2 <- length(oldstats)
	if(length(newstats) != J2) stop("error in relabel.output -- length(oldstats) != length(newstats)")
	if(J2 > 0) {
		for(j in 1:J2) {
			idx <- fmatch(oldstats[j],names(o$stats))
			if(is.na(idx)) stop("error in relabel.output -- oldstats not found in stats")
			names(o$stats)[idx] <- newstats[j]
			if(!is.na(fmatch("statsse",names(o)))) names(o$statsse)[idx] <- newstats[j]
		}
	}
	o
}

combine.output <- function(os)
{
	J <- length(os)
	coef <- list()
	se <- list()
	stats <- list()
	for(j in 1:J) {
		coef[[j]] <- os[[j]]$coef
		se[[j]] <- os[[j]]$se
		stats[[j]] <- os[[j]]$stats
	}
	o <- list()
	o$coef <- combine.matrix(coef)
	o$se <- combine.matrix(se)
	dims <- logical(0)
	for(j in 1:J) dims <- c(dims,ncol(os[[j]]$coef))
	o$stats <- combine.matrix.list(stats,dims)
	hasstatsse <- F
	for(j in 1:J) if(!is.na(fmatch("statsse",names(os[[j]])))) hasstatsse <- T
	if(hasstatsse) {
		statsse <- list()
		for(j in 1:J) statsse[[j]] <- os[[j]]$statsse
		labs <- names(o$stats)
		o$statsse <- combine.matrix.list(statsse,dims,labs)	
	}
	o
}

combine.matrix <- function(Xs)
{
	J <- length(Xs)
	if(J < 2) stop("error in combine.matrix -- J < 2")
	rs <- rownames(Xs[[1]])
	cs <- colnames(Xs[[1]])
	L <- ncol(Xs[[1]])
	for(j in 2:J) {
		rs <- c(rs,rownames(Xs[[j]]))
		cs <- c(cs,colnames(Xs[[j]]))
		L <- L + ncol(Xs[[1]])
	}
	rs <- unique(rs)
	K <- length(rs)
	X <- matrix(rep(NA,K*L),ncol=L)
	Curr <- 1
	for(j in 1:J) {
		for(k in 1:nrow(Xs[[j]])) X[fmatch(rownames(Xs[[j]]),rs),Curr:(Curr+ncol(Xs[[j]])-1)] <- Xs[[j]]
		Curr <- Curr + ncol(Xs[[j]])
	}
	rownames(X) <- rs
	colnames(X) <- cs	
	X
}

combine.matrix.list <- function(Xs,dims,labs=logical(0))
{
	J <- length(Xs)
	if(J < 2) stop("error in combine.matrix -- J < 2")
	rs <- logical(0)
	L <- 0
	for(j in 1:J) {
		rs <- c(rs,names(Xs[[j]]))
		if(length(Xs[[j]]) > 0) if(length(Xs[[j]][[1]]) != dims[j]) stop("error in combine.matrix.list")
		L <- L + dims[j]
	}
	rs <- unique(rs)
	if(length(labs) > 0) rs <- labs
	K <- length(rs)
	X <- list()
	for(i in 1:length(rs)) {
		temp <- logical(0)
		for(j in 1:J) {
			idx <- fmatch(rs[i],names(Xs[[j]]))
			if(is.na(idx)) {
				temp <- c(temp,rep(NA,dims[j]))
			} else {
				temp <- c(temp,Xs[[j]][[idx]])
			}
		}
		X[[i]] <- temp
	}
	names(X) <- rs
	X
}

print.output <- function(o,kcoef=3,kstat=3)
{
	J <- ncol(o$coef)
	ivs <- rownames(o$coef)
	stats <- names(o$stats)	
	v1 <- c("","Variable",ivs,stats)
	K <- length(o$stats)
	dig_stats <- list()
	if(length(o$stats) >= 1) {
		for(i in 1:length(o$stats)) {
			if(is.numeric(o$stats[[i]][1])) {
				dig_stats[[i]] <- as.character(as.numeric(dig(o$stats[[i]],kstat)))
			} else {
				dig_stats[[i]] <- o$stats[[i]]
			}
		}
		names(dig_stats) <- names(o$stats)
	}

	if(!is.na(fmatch("statsse",names(o)))) {
		dig_statsse <- list()
		if(length(o$statsse) >= 1) {
			for(i in 1:length(o$statsse)) {
				dig_statsse[[i]] <- as.se(as.double(o$statsse[[i]]))
			}
		}
	}

	v2 <- rbind(colnames(o$coef),rep("Coef.",J),as.coef(o$coef,o$se,k=kcoef))
	if(length(dig_stats) >= 1) {
		for(i in 1:length(dig_stats)) {
			v2 <- rbind(v2,dig_stats[[i]])
		}
	}

	if(is.na(fmatch("statsse",names(o)))) {
		v3 <- rbind(rep("",J),rep("(s.e.)",J),as.se(o$se,k=kcoef),matrix(rep(NA,J*K),ncol=J))		
	} else {
		v3 <- rbind(rep("",J),rep("(s.e.)",J),as.se(o$se,k=kcoef))
		if(length(o$statsse) >= 1) {
			for(i in 1:length(o$statsse)) {
				v3 <- rbind(v3,dig_statsse[[i]])
			}
		}
	}
	v1 <- pad0(v1)
	for(j in 1:J) {
		v2[,j] <- pad0(v2[,j])
		v3[,j] <- pad0(v3[,j])
		v2[,j] <- paste(v2[,j],v3[,j],sep=" ")
	}
	for(i in 1:length(v1)) print0(paste(c(v1[i],v2[i,]),collapse=" "))
}

as.coef <- function(coef,se,k=3,p.val=logical(0),sigbase=logical(0))
{
	if(length(p.val) == 0) {
		if(is.matrix(coef)) {
			res <- coef
			if(length(sigbase) == 0) {
				for(i in 1:ncol(coef)) res[,i] <- paste(dig(coef[,i],k=k),stars(coef[,i],se[,i]),sep="")
			} else {
				for(i in 1:ncol(coef)) res[,i] <- paste(dig(coef[,i],k=k),stars(coef[,i],se[,i],sigbase=sigbase[i]),sep="")
			}
			res
		} else {
			paste(dig(coef,k=k),stars(coef,se,sigbase=sigbase),sep="")
		}
	} else {
		if(is.matrix(coef)) {
			res <- coef
			if(length(sigbase) == 1) {
				for(i in 1:ncol(coef)) res[,i] <- paste(dig(coef[,i],k=k),stars.pval(coef[,i],p.val[,i],sigbase=sigbase),sep="")
			} else {
				for(i in 1:ncol(coef)) res[,i] <- paste(dig(coef[,i],k=k),stars.pval(coef[,i],p.val[,i],sigbase=sigbase[i]),sep="")
			}
			res
		} else {
			paste(dig(coef,k=k),stars.pval(p.val,sigbase=sigbase),sep="")
		}
	}
}

as.se <- function(se,k=3)
{
	if(is.matrix(se)) {
		res <- se
		for(i in 1:ncol(se)) res[,i] <- str_replace_all(paste("(",dig(se[,i],k),")",sep=""),"\\(\\)","")
		res
	} else {
		str_replace_all(paste("(",dig(se,k),")",sep=""),"\\(\\)","")
	}
}

pval.as.pval <- function(pval,k=3)
{
	paste(dig(pval,k),stars.pval(pval),sep="")
}

stars.scalar <- function(coef,se,sigbase=logical(0),sigalt="^")
{
	if(is.na(coef)) {
		""
	} else if(is.na(se)) {
		"?"
	} else {
		pval1 <- pval(coef,se,sigbase)
		if(is.nan(pval1)) {
			"?"
		} else {
			check1 <- length(sigbase) == 0
			if(!check1) check1 <- sigbase == 0
			if(check1) {
				if(pval1 <= 0.001) {
					"***"
				} else if(pval1 <= 0.01) {
					"**"
				} else if(pval1 <= 0.05) {
					"*"
				} else if(pval1 <= 0.1) {
					"+"
				} else {
					""
				}
			} else {
				if(pval1 <= 0.05) {
					sigalt
				} else {
					""
				}
			}
		}
	}
}

stars <- function(coef,se,sigbase=logical(0))
{
	if(is.matrix(coef))
	{
		m <- nrow(coef)
		n <- ncol(coef)
		res <- coef
		if(length(sigbase) == 0) {
			for(i in 1:m) for(j in 1:n) res[i,j] <- stars.scalar(coef[i,j],se[i,j])
		} else {
			for(i in 1:m) for(j in 1:n) res[i,j] <- stars.scalar(coef[i,j],se[i,j],sigbase[j])
		}
	} else {
		m <- length(coef)
		res <- coef
		if(length(sigbase) == 0) {
			for(i in 1:m) res[i] <- stars.scalar(coef[i],se[i])
		} else if(length(sigbase) == 1) {
			for(i in 1:m) res[i] <- stars.scalar(coef[i],se[i],sigbase=sigbase)
		} else {
			for(i in 1:m) res[i] <- stars.scalar(coef[i],se[i],sigbase=sigbase[i])
		}
	}
	res
}

stars.pval <- function(pval1,sigbase=logical(0))
{
	n <- length(pval1)
	ret <- rep(NA,n)
	check1 <- length(sigbase) == 0
	if(!check1) check1 <- sigbase == 0
	if(check1) {
		for(i in 1:n) {
			if(pval1[i] <= 0.001) {
				ret[i] <- "***"
			} else if(pval1[i] <= 0.01) {
				ret[i] <- "**"
			} else if(pval1[i] <= 0.05) {
				ret[i] <- "*"
			} else if(pval1[i] <= 0.1) {
				ret[i] <- "+"
			} else {
				ret[i] <- ""
			}
		}
	} else {
		for(i in 1:n) {
			if(pval1[i] <= 0.001) {
				ret[i] <- "^^^"
			} else if(pval1[i] <= 0.01) {
				ret[i] <- "^^"
			} else if(pval1[i] <= 0.05) {
				ret[i] <- "^"
			} else {
				ret[i] <- ""
			}
		}
	}
	ret
}

pval <- function(est,se,sigbase=logical(0))
{
	if(length(sigbase) == 0) {
		2*pnorm(-abs(est/se))
	} else if(length(sigbase) == 1) {
		2*pnorm(-abs((est-sigbase)/se))
	} else {
		stop("error in pval -- length(sigbase) != 0 or 1")
	}
}

alternate <- function(x,y)
{
	if(is.matrix(x)) {
		m <- nrow(x)
		n <- ncol(x)
		res <- matrix(rep(NA,length(x)*2),ncol=n)
		for(i in 1:n) {
			res[,i] <- as.vector(t(matrix(c(x[,i],y[,i]),nrow=m)))
		}
		res
	} else {
		n <- length(x)
		if(length(y) != n) {
			error("Error with alternate --- incompadible dimensions")
		}
		as.vector(t(matrix(c(x,y),nrow=n)))
	}
}

pad0 <- function(x)
{
	K <- length(x)
	x[is.na(x)] <- ""
	len <- max(nchar(x))
	for(k in 1:K) if(nchar(x[k]) < len) x[k] <- paste(x[k],paste(rep(" ",len-nchar(x[k])),collapse=""),sep="")
	x
}

print0 <- function(s1,s2=logical(0))
{
	if(length(s2) == 0)
	{
		print(s1)
		flush.console()
	} else {
		print(paste(s1,": ",s2,sep=""))
		flush.console()
	}
}

mnl <- function(Y,X,Ind,Choice,Cluster,Opt="logit",R1=1000,R2=10000,MaxIter=1000,RandomSeed=-23498723,subset=logical(0),ExtraCluster=logical(0),Test=1,SkipInference=0,FeFac=.1)
{
	fastr_dll_loc <- paste("D:\\Programming\\Projects\\fastr\\x64\\Release\\fastr.dll",sep="")
	dyn.load(fastr_dll_loc)

	if(length(Y) != nrow(X) | length(Y) != length(Ind) | length(Y) != length(Choice) | length(Y) != length(Cluster))
	{
		str1 <- "error in mnl -- incompadible dimensions: \n"
		str1 <- paste(str1,"length(Y): ",length(Y),"\n",sep="")
		str1 <- paste(str1,"nrow(X): ",nrow(X),"\n",sep="")
		str1 <- paste(str1,"length(Ind): ",length(Ind),"\n",sep="")
		str1 <- paste(str1,"length(Choice): ",length(Choice),"\n",sep="")
		str1 <- paste(str1,"length(Cluster): ",length(Cluster),sep="")
		stop(str1)
	}

	if(Test != 1 & Test != 2) stop("error -- invalid test value")
	
	if(SkipInference != 0 & SkipInference != 1) stop("error -- invalid value for SkipInference")

	if(FeFac < 0) stop("error -- invalid value for FeFac")

	if(length(colnames(X)) == 0) colnames(X) <- paste("iv",1:ncol(X),sep="")
	
	if(length(subset) == 0) {
		YA <- Y
		XA <- X
		IndA <- Ind
		ChoiceA <- Choice
		ClusterA <- Cluster
		ClusterB <- ExtraCluster1
		E1 <- length(ClusterB)
	} else if(length(subset) == length(Y)) {
		YA <- Y[subset]
		XA <- X[subset,]
		IndA <- Ind[subset]
		ChoiceA <- Choice[subset]
		ClusterA <- Cluster[subset]
		if(length(ExtraCluster) > 0) {
			ClusterB <- ExtraCluster[subset]
			E1 <- length(ClusterB)

		} else {
			ClusterB <- 1
			E1 <- 0
		}
	}
	E2 <- 0
	if(E1 > 0) {
		ExtraClusters <- sort(unique(ClusterB))
		Temp <- fmatch(ClusterB,ExtraClusters)
		ClusterB <- Temp	
	}

	N <- length(YA)
	KX <- ncol(as.matrix(XA))
	YMiss <- is.na(YA)
	YA[YMiss] <- 0
	XMiss <- is.na(XA)
	XA[XMiss] <- 0
	Inds <- sort(unique(IndA))
	Clusters <- sort(unique(ClusterA))
	Ind1 <- fmatch(IndA,Inds)
	Cluster1 <- fmatch(ClusterA,Clusters)
	Theta <- rep(0,KX)
	ThetaSe <- rep(0,KX)
	ThetaVar <- rep(0,KX^2)
	I2 <- 0
	N2 <- 0
	C2 <- 0
	J2 <- 0
	Cluster2 <- rep(0,length(Clusters))

	if(Opt == "logit") {
		Opt2 <- 1
	} else if(Opt == "relogit") {
		Opt2 <- 2
	} else if(Opt == "cmdlogit1") {
		Opt2 <- 3
	} else if(Opt == "cmdlogit2") {
		Opt2 <- 4
	} else if(Opt == "relogitbayes") {
		Opt2 <- 5
	} else if(Opt == "reprobitbayes") {
		Opt2 <- 6
	} else if(Opt == "felogit") {
		Opt2 <- 7
	} else {
		stop("Invalid option")
	}
	Delta <- rep(0,length(Clusters)*length(unique(ChoiceA)))
	ClusterChoiceSet <- rep(0,length(Clusters)*length(unique(ChoiceA)))
	obj <- 0
	bic <- 0
	aic <- 0
	ret <- .C("mnl",PACKAGE="fastr",Y = as.integer(YA),
			YMiss = as.integer(YMiss),
			X = as.double(XA),
			XMiss = as.integer(XMiss),
			Ind = as.integer(Ind1),
			Choice = as.integer(ChoiceA),
			Cluster = as.integer(Cluster1),
			Theta = as.double(Theta),
			ThetaSe = as.double(ThetaSe),
			ThetaVar = as.double(ThetaVar),
			N = as.integer(N),
			KX = as.integer(KX),
			I2 = as.integer(I2),
			N2 = as.integer(N2),
			C2 = as.integer(C2),
			J2 = as.integer(J2),
			Clusters = as.integer(Cluster2),
			Option = as.integer(Opt2),
			R1 = as.integer(R1),
			R2 = as.integer(R2),
			MaxIter = as.integer(MaxIter),
			RandomSeed = as.integer(RandomSeed),
			ClusterChoiceSet = as.integer(ClusterChoiceSet),
			Delta = as.double(Delta),
			Objective = as.double(obj),
			BIC = as.double(bic),
			AIC = as.double(aic),
			E1 = as.integer(E1),
			ExtraCluster = as.integer(ClusterB),
			E2 = as.integer(E2),
			Test = as.integer(Test),
			SkipInference = as.integer(SkipInference),
			FeFac = as.double(FeFac))
	dyn.unload(fastr_dll_loc)
	if(Opt == "felogit") {
		ClusterChoiceSet <- t(matrix(ret$ClusterChoiceSet[1:(ret$J2*ret$C2)],nrow=ret$J2))
		ClusterChoiceSet1 <- as.vector(t(ClusterChoiceSet))
		Delta <- rep(NA,ret$J2*ret$C2)
		Delta[ClusterChoiceSet1==1] <- ret$Delta[1:sum(ClusterChoiceSet)]
		Delta <- t(matrix(Delta,nrow=ret$J2))
		Delta[,1] <- 0
		rownames(ClusterChoiceSet) <- Clusters[ret$Clusters[1:ret$C2]]
		rownames(Delta) <- Clusters[ret$Clusters[1:ret$C2]]
	} else {
		ClusterchoiceSet <- logical(0)
		Delta <- logical(0)
	}
	mod <- list()
	mod$theta <- ret$Theta
	mod$se <- ret$ThetaSe
	mod$V <- matrix(ret$ThetaVar,nrow=KX)
	mod$ivs <- colnames(X)
	mod$stats <- list()
	mod$stats$I <- ret$I2
	mod$stats$N <- ret$N2
	mod$stats$C <- ret$C2
	mod$J <- ret$J2
	mod$ClusterNames <- Clusters[ret$Clusters[1:ret$C2]]
	mod$ClusterChoiceSet <- ClusterChoiceSet
	mod$Delta <- Delta
	mod$stats$obj <- ret$Objective
	mod$stats$bic <- ret$BIC
	mod$stats$aic <- ret$AIC
	mod$stats$C2 <- ret$E2
	mod$coef <- ret$Theta
	mod
}

# compute variance-covariance matrix for func1(betahat), where func1 is vector-valued
delta.method <- function(func1,beta,V,...)
{
	c_beta <- jacobian(func1,beta,method="simple",...)
	Vc <- c_beta %*% V %*% t(c_beta)
	list(est=func1(beta,...),se=sqrt(diag(Vc)),V=Vc)
}


# test of a vector of nonlinear restrictions
wald.test <- function(func1,beta,V,...)
{
	dm <- delta.method(func1,beta,V,...)
	cbeta <- func1(beta,...)
	W <- t(cbeta ) %*% solve(dm$V) %*% cbeta
	pval <- 1 - pchisq(W,length(dm$est))
	list(W=W,pval=pval)
}

latex_add_line <- function(file1,s)
{
	cat(s,file=file1,sep="\n",append=TRUE)
}

latex_table_entry <- function(file1,name,coef,bold=FALSE,italic=FALSE)
{
	if(bold)
	{
		name <- paste("\\textbf{",name,"}",sep="")
		coef <- paste("\\textbf{",coef,"}",sep="")
	}
	if(italic)
	{
		name <- paste("\\textit{",name,"}",sep="")
		coef <- paste("\\textit{",coef,"}",sep="")
	}
	s <- name
	n <- length(coef)
	for(i in 1:n) if(is.na(coef[i])) { coef[i] <- "" }
	if(n > 1) for(i in 1:(n-1)) { s <- paste(s," & ",coef[i],sep="") }
	s <- paste(s," & ",coef[n]," \\\\ \n",sep="")
	s
	cat(s,file=file1,sep="\n",append=TRUE)
}

latex_table_entries <- function(file1,names,coefs,bold=FALSE,italic=FALSE)
{
	m <- length(names)
	for(j in 1:m) latex_table_entry(file1,names[j],coefs[j,],bold)
}

latex_model <- function(file1,names,o1,kcoef=3,kstat=3,eqlabels=TRUE,eqlabelsskip=TRUE,stats=logical(0),sigbase=logical(0),modellab="")
{
	m <- length(names)
	n <- ncol(o1$coef)
	if(length(stats) > 0) {
		stats1 <- logical(0)
		stats1 <- drop.na(fmatch(stats,names(o1$stats)))
	} else if(length(o1$stats) > 0) {
		stats1 <- 1:length(o1$stats)
	}
	
	if(eqlabels) {
		if(modellab == "") {
			latex_table_entry(file1,"",colnames(o1$coef))
		} else {
			latex_table_entry(file1,paste("\\textbf{",modellab,":}",sep=""),colnames(o1$coef))
		}
	}
	if(eqlabelsskip) latex_add_line(file1," \\\\")
	latex_add_line(file1,"\\textbf{Independent Variables:}\\\\")
	for(j in 1:m) {
		if(length(sigbase) == 0) {
			latex_table_entry(file1,paste("\\hspace{.4cm}",names[j],sep=""),as.coef(o1$coef[j,],o1$se[j,],k=kcoef))
		} else if(length(sigbase) == n) {
			latex_table_entry(file1,paste("\\hspace{.4cm}",names[j],sep=""),str_replace_all(as.coef(o1$coef[j,],o1$se[j,],k=kcoef,sigbase=sigbase),"\\^","\\\\^{}"))
		} else {
			stop("error in latex_model -- incompadible dimensions")
		}
		latex_table_entry(file1,"",as.se(o1$se[j,],k=kcoef))
	}
	latex_add_line(file1,"\\\\")

	if(length(stats1) > 0) {
		for(j in 1:length(stats1)) {
			dig_stats <- o1$stats[[stats1[j]]]
			if(length(kstat) == 1) {
				if(names(o1$stats)[j] == "N" | names(o1$stats)[j] == "Clusters" | names(o1$stats)[j] == "C") {
					dig_stats <- dig(dig_stats,0)
				} else {
					if(is.double(dig_stats)) {
						if(length(kstat) == 1) {
							dig_stats <- dig(dig_stats,k=kstat)
						} else {
							dig_stats <- dig(dig_stats,k=kstat[j])
						}
					} else {
						dig_stats <- str_replace_all(dig_stats,"\\^","\\\\^{}")
					}
				}
			} else {
				dig_stats <- dig(dig_stats,k=kstat[j])
			}
			if(names(o1$stats)[stats1[j]] == "r.squared") {
				latex_table_entry(file1,"\\textbf{R-Squared}",dig_stats)
			} else {
				latex_table_entry(file1,paste("\\textbf{",names(o1$stats)[stats1[j]],"}",sep=""),dig_stats)
			}
		}
	}
}

latex_doc_start <- function(file1,packages=logical(0))
{
	cat("\\documentclass[11pt]{article}",file=file1,sep="\n")
	s <- "\\usepackage{float,amsmath,amssymb,amsthm,fullpage,setspace,natbib,enumerate,url,multirow,lscape"
	if(length(packages) > 0) for(i in 1:length(packages)) s <- paste(s,",",packages[i],sep="")
	s <- paste(s,"}",sep="")
	cat(s,file=file1,sep="\n",append=TRUE)
	#cat("\\usepackage[dvips]{graphicx,xcolor}",file=file1,sep="\n",append=TRUE)
	cat("\\onehalfspacing",file=file1,sep="\n",append=TRUE)
	cat("\\begin{document}",file=file1,sep="\n\n",append=TRUE)
}

latex_doc_end <- function(file1)
{
	cat("\\end{document}",file=file1,sep="\n",append=TRUE)
}

latex_table_start <- function(file1,k)
{
	cat("\\begin{table}[htp]\\centering\\scriptsize",file=file1,sep="\n",append=TRUE)
	cat("\\begin{singlespace}",file=file1,sep="\n",append=TRUE)
	cat("\\begin{tabular}{ l ",paste(rep("c",k),collapse=" ")," } \\hline \\hline",file=file1,sep="\n",append=TRUE)
}

latex_table_end <- function(file1,caption="",label="")
{
	cat("\\hline \\hline",file=file1,sep="\n",append=TRUE)
	cat("\\end{tabular}",file=file1,sep="\n",append=TRUE)
	cat("\\end{singlespace}",file=file1,sep="\n",append=TRUE)
	if(caption != "") cat(paste("\\caption{\\footnotesize{",caption,"}}",sep=""),file=file1,sep="\n",append=TRUE)
	if(label != "") cat(paste("\\label{",label,"}",sep=""),file=file1,sep="\n",append=TRUE)
	cat("\\end{table}",file=file1,sep="\n",append=TRUE)
}

#################
# main analysis #
#################

# Table 1 -- Positive vs. Negative Advertising by Year #

addata <- list()
addata[[1]] <- ads2000
addata[[2]] <- ads2004
addata[[3]] <- ads2008
addata[[4]] <- ads2012
addata[[5]] <- ads2016
years <- c("2000","2004","2008","2012","2016")

posnegtab <- matrix(rep(NA,5*4),ncol=5)

# pos vs. neg, general
posnegtab[1,1] <- dig0(sum0(as.numeric(addata[[1]]$grp)[str_split_vec(addata[[1]]$type,"_")[,1]=="Gen"&str_split_vec(addata[[1]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[2,1] <- dig0(sum0(as.numeric(addata[[1]]$grp)[str_split_vec(addata[[1]]$type,"_")[,1]=="Gen"&(str_split_vec(addata[[1]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[1]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[1,2] <- dig0(sum0(as.numeric(addata[[2]]$grp)[str_split_vec(addata[[2]]$type,"_")[,1]=="Gen"&str_split_vec(addata[[2]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[2,2] <- dig0(sum0(as.numeric(addata[[2]]$grp)[str_split_vec(addata[[2]]$type,"_")[,1]=="Gen"&(str_split_vec(addata[[2]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[2]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[1,3] <- dig0(sum0(as.numeric(addata[[3]]$grp)[str_split_vec(addata[[3]]$type,"_")[,1]=="Gen"&str_split_vec(addata[[3]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[2,3] <- dig0(sum0(as.numeric(addata[[3]]$grp)[str_split_vec(addata[[3]]$type,"_")[,1]=="Gen"&(str_split_vec(addata[[3]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[3]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[1,4] <- dig0(sum0(as.numeric(addata[[4]]$grp)[str_split_vec(addata[[4]]$type,"_")[,1]=="Gen"&str_split_vec(addata[[4]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[2,4] <- dig0(sum0(as.numeric(addata[[4]]$grp)[str_split_vec(addata[[4]]$type,"_")[,1]=="Gen"&(str_split_vec(addata[[4]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[4]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[1,5] <- dig0(sum0(as.numeric(addata[[5]]$grp)[str_split_vec(addata[[5]]$type,"_")[,1]=="Gen"&str_split_vec(addata[[5]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[2,5] <- dig0(sum0(as.numeric(addata[[5]]$grp)[str_split_vec(addata[[5]]$type,"_")[,1]=="Gen"&(str_split_vec(addata[[5]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[5]]$type,"_")[,2]=="ProContrast")]) / 1000)

# pos vs. neg, primary
posnegtab[3,1] <- dig0(sum0(as.numeric(addata[[1]]$grp)[str_split_vec(addata[[1]]$type,"_")[,1]=="Prim"&str_split_vec(addata[[1]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[4,1] <- dig0(sum0(as.numeric(addata[[1]]$grp)[str_split_vec(addata[[1]]$type,"_")[,1]=="Prim"&(str_split_vec(addata[[1]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[1]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[3,2] <- dig0(sum0(as.numeric(addata[[2]]$grp)[str_split_vec(addata[[2]]$type,"_")[,1]=="Prim"&str_split_vec(addata[[2]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[4,2] <- dig0(sum0(as.numeric(addata[[2]]$grp)[str_split_vec(addata[[2]]$type,"_")[,1]=="Prim"&(str_split_vec(addata[[2]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[2]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[3,3] <- dig0(sum0(as.numeric(addata[[3]]$grp)[str_split_vec(addata[[3]]$type,"_")[,1]=="Prim"&str_split_vec(addata[[3]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[4,3] <- dig0(sum0(as.numeric(addata[[3]]$grp)[str_split_vec(addata[[3]]$type,"_")[,1]=="Prim"&(str_split_vec(addata[[3]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[3]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[3,4] <- dig0(sum0(as.numeric(addata[[4]]$grp)[str_split_vec(addata[[4]]$type,"_")[,1]=="Prim"&str_split_vec(addata[[4]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[4,4] <- dig0(sum0(as.numeric(addata[[4]]$grp)[str_split_vec(addata[[4]]$type,"_")[,1]=="Prim"&(str_split_vec(addata[[4]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[4]]$type,"_")[,2]=="ProContrast")]) / 1000)

posnegtab[3,5] <- dig0(sum0(as.numeric(addata[[5]]$grp)[str_split_vec(addata[[5]]$type,"_")[,1]=="Prim"&str_split_vec(addata[[5]]$type,"_")[,2]=="Promote"]) / 1000)
posnegtab[4,5] <- dig0(sum0(as.numeric(addata[[5]]$grp)[str_split_vec(addata[[5]]$type,"_")[,1]=="Prim"&(str_split_vec(addata[[5]]$type,"_")[,2]=="ProAttack"|str_split_vec(addata[[5]]$type,"_")[,2]=="ProContrast")]) / 1000)

# Figure 1 -- Temporal Pattterns of Advertising

### design plot ###

## some plots ##

Dmeans <- list()
Rmeans <- list()
data1 <- read_excel(paste(dir1,"list_of_states_in_each_dma.xlsx",sep=""))
for(i in 1:5)
{
	curryear <- years[i]

	data2 <- read_excel(paste(dir1,"state_primaries.xlsx",sep=""),sheet=curryear)
	data3 <- read_excel(paste(dir1,"dma_codes.xlsx",sep=""),sheet=curryear)
	
	# get list of dates
	dates <- (min0(as.Date(addata[[i]]$date)) - as.Date("1/1/1980",format="%m/%d/%Y") - 50):(max0(as.Date(addata[[i]]$date)) - as.Date("1/1/1980",format="%m/%d/%Y"))
	dmas <- sort(unique(data3$dma))
	m <- length(dates)
	p <- length(dmas)
	t <- as.Date(addata[[i]]$date,format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
	
	if(curryear == "2000") {
		dems <- c("Gore","Bradley","NoOneD")
		reps <- c("McCain","Bush","Forbes","Bauer","Keyes","NoOneR")
	} else if(curryear == "2004") {
		dems <- c("Dean","Edwards","Gephardt","Kerry","Lieberman","Clark","Kucinich","NoOneD")
	} else if(curryear == "2008") {
		dems <- c("Obama","Edwards","Clinton","Biden","Dodd","Richardson","Kucinich","NoOneD")
		reps <- c("Huckabee","Giuliani","Thompson","Tancredo","Hunter","Romney","McCain","Paul","NoOneR")
	} else if(curryear == "2012") {
		reps <- c("Daniels","Romney","Pataki","Pawlenty","Bachmann","Paul","Huntsman","Cain","Perry","Gingrich","Santorum","Palin","Roemer","NoOneR")
	} else if(curryear == "2016") {
		dems <- c("Clinton","Sanders","O'Malley","Lessig","NoOneD")
		reps <- c("Bush","Carson","Christie","Cruz","Fiorina","Gilmore","Graham","Huckabee","Jindal","Kasich","Pataki","Paul","Perry","Rubio","Santorum","Trump","Walker","NoOneR")
	}

	demad <- !is.na(fmatch(str_split_vec(addata[[i]]$type,"_")[,3],dems)) & is.na(str_match(addata[[i]]$type,"Gen")) & is.na(str_match(addata[[i]]$type,"Anti"))
	repad <- !is.na(fmatch(str_split_vec(addata[[i]]$type,"_")[,3],reps)) & is.na(str_match(addata[[i]]$type,"Gen")) & is.na(str_match(addata[[i]]$type,"Anti"))

	if(curryear != 2012) {
		XD <- matrix(rep(0,m*p),nrow=m)
		XD[cbind(fmatch(t[demad],dates),fmatch(addata[[i]]$dma[demad],dmas))] <- as.numeric(addata[[i]]$grp[demad])
		demdate_1 <- as.Date(data2$democratic_primary[fmatch(data1$dma_state_1,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		demdate_2 <- as.Date(data2$democratic_primary[fmatch(data1$dma_state_2,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		demdate_3 <- as.Date(data2$democratic_primary[fmatch(data1$dma_state_3,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		demdate_4 <- as.Date(data2$democratic_primary[fmatch(data1$dma_state_4,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		demdate_5 <- as.Date(data2$democratic_primary[fmatch(data1$dma_state_5,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		tillprimD <- matrix(rep(0,m*p),nrow=m)
	}
	if(curryear != "2004") {
		XR <- matrix(rep(0,m*p),nrow=m)
		XR[cbind(fmatch(t[repad],dates),fmatch(addata[[i]]$dma[repad],dmas))] <- as.numeric(addata[[i]]$grp[repad])
		repdate_1 <- as.Date(data2$republican_primary[fmatch(data1$dma_state_1,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		repdate_2 <- as.Date(data2$republican_primary[fmatch(data1$dma_state_2,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		repdate_3 <- as.Date(data2$republican_primary[fmatch(data1$dma_state_3,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		repdate_4 <- as.Date(data2$republican_primary[fmatch(data1$dma_state_4,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		repdate_5 <- as.Date(data2$republican_primary[fmatch(data1$dma_state_5,data2$state_abb)],format="%Y-%m-%d") - as.Date("1/1/1980",format="%m/%d/%Y")
		tillprimR <- matrix(rep(0,m*p),nrow=m)
	}

	for(j in 1:p)
	{
		if(curryear != "2012") {
			till_D_1 <- demdate_1[fmatch(dmas[j],data1$dma_code)] - dates
			till_D_2 <- demdate_2[fmatch(dmas[j],data1$dma_code)] - dates
			till_D_3 <- demdate_3[fmatch(dmas[j],data1$dma_code)] - dates
			till_D_4 <- demdate_4[fmatch(dmas[j],data1$dma_code)] - dates
			till_D_5 <- demdate_5[fmatch(dmas[j],data1$dma_code)] - dates

			temp <- cbind(till_D_1,till_D_2,till_D_3,till_D_4,till_D_5)
			temp[temp<0] <- NA
			till_D <- rowMins(temp,na.rm=TRUE)
			till_D[is.infinite(till_D)] <- rowMaxs(cbind(till_D_1,till_D_2,till_D_3,till_D_4,till_D_5),na.rm=TRUE)[is.infinite(till_D)]
	
			tillprimD[,j] <- till_D
		}

		if(curryear != "2004") {
			till_R_1 <- repdate_1[fmatch(dmas[j],data1$dma_code)] - dates
			till_R_2 <- repdate_2[fmatch(dmas[j],data1$dma_code)] - dates
			till_R_3 <- repdate_3[fmatch(dmas[j],data1$dma_code)] - dates
			till_R_4 <- repdate_4[fmatch(dmas[j],data1$dma_code)] - dates
			till_R_5 <- repdate_5[fmatch(dmas[j],data1$dma_code)] - dates

			temp <- cbind(till_R_1,till_R_2,till_R_3,till_R_4,till_R_5)
			temp[temp<0] <- NA
			till_R <- rowMins(temp,na.rm=TRUE)
			till_R[is.infinite(till_R)] <- rowMaxs(cbind(till_R_1,till_R_2,till_R_3,till_R_4,till_R_5),na.rm=TRUE)[is.infinite(till_R)]
			
			tillprimR[,j] <- till_R
		}
	}

	# grps
	if(curryear != "2012") Dmeans[[curryear]] <- mean0(as.vector(XD),by=as.vector(tillprimD))
	if(curryear != "2004") Rmeans[[curryear]] <- mean0(as.vector(XR),by=as.vector(tillprimR))
}

# the plot ##
pdf(file=paste(dir1,"design.pdf",sep=""),width=8,height=6)
par(mfrow=c(2,3))
for(curryear in c("2000","2004","2008","2012","2016"))
{
	plot(0:1,type='n',xlim=c(-80,40),ylim=c(0,250),main=curryear,xlab="Days Until Primary",ylab="Average GRPs")
	if(curryear != 2012) points(-as.numeric(names(Dmeans[[curryear]])),Dmeans[[curryear]],type='l',col='blue')
	if(curryear != 2004) points(-as.numeric(names(Rmeans[[curryear]])),Rmeans[[curryear]],type='l',col='red')
	abline(v=0,lty=2)
	abline(v=-14,lty=2)
	abline(v=-28,lty=2)
	abline(v=-56,lty=2)
}
dev.off()

# various numbers on page 18:

# Obama, 2008
dig0(sum0(as.numeric(ads2008$grp),subset=str_split_vec(ads2008$type,"_")[,1]=="Prim"&str_split_vec(ads2008$type,"_")[,3]=="Obama") / 184)

# Clinton, 2008
dig0(sum0(as.numeric(ads2008$grp),subset=str_split_vec(ads2008$type,"_")[,1]=="Prim"&str_split_vec(ads2008$type,"_")[,3]=="Clinton") / 184)

# Sanders, 2016
dig0(sum0(as.numeric(ads2016$grp),subset=str_split_vec(ads2016$type,"_")[,1]=="Prim"&str_split_vec(ads2016$type,"_")[,3]=="Sanders") / 211)

# Romney, 2008
dig0(sum0(as.numeric(ads2008$grp),subset=str_split_vec(ads2008$type,"_")[,1]=="Prim"&str_split_vec(ads2008$type,"_")[,3]=="Romney") / 184)

# Romney, 2012
dig0(sum0(as.numeric(ads2012$grp),subset=str_split_vec(ads2012$type,"_")[,1]=="Prim"&str_split_vec(ads2012$type,"_")[,3]=="Romney") / 202)

# Bush, 2000
dig0(sum0(as.numeric(ads2000$grp),subset=str_split_vec(ads2000$type,"_")[,1]=="Prim"&str_split_vec(ads2000$type,"_")[,3]=="Bush") / 75)

# Table 2 -- The Effects of Ads on Favorability and Candidate Choice

pro <- grp_4wk_p / 1000
runanti <- (grp_4wk_pa + grp_4wk_pc) / 1000
anti <- (grp_4wk_aa + grp_4wk_ac) / 1000

# favorability models
lm1_14 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oMain1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oMain1 <- relabel.output(oMain1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oMain1 <- relabel.output(oMain1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oMain1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oMain3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oMain3 <- relabel.output(oMain3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oMain3,kstat=0)

oMain <- combine.output(list(oMain1,oMain3))
print.output(oMain,kstat=3)

# save main models for later
lm14_main <- lm1_14
lm28_main <- lm1_28
lm56_main <- lm1_56
mnlint14_main <- mnlint14
mnlint28_main <- mnlint28
mnlint56_main <- mnlint56

# the numbers on page 20
dig1(100*(exp(mnlint14_main$coef[1]) / (1 + exp(mnlint14_main$coef[1])) - .5))
dig1(100*(exp(mnlint28_main$coef[1]) / (1 + exp(mnlint28_main$coef[1])) - .5))
dig1(100*(exp(mnlint56_main$coef[1]) / (1 + exp(mnlint56_main$coef[1])) - .5))

dig1(100*(exp(mnlint14_main$coef[2]-mnlint14_main$coef[3]) / (1 + exp(mnlint14_main$coef[2]-mnlint14_main$coef[3])) - .5))
dig1(100*(exp(mnlint28_main$coef[2]-mnlint28_main$coef[3]) / (1 + exp(mnlint28_main$coef[2]-mnlint28_main$coef[3])) - .5))
dig1(100*(exp(mnlint56_main$coef[2]-mnlint56_main$coef[3]) / (1 + exp(mnlint56_main$coef[2]-mnlint56_main$coef[3])) - .5))

# Table 3 -- Relative Effectiveness of Positive Advertising

## DIFFERENT THAN PAPER!! ##

me_tab1 <- matrix(rep(NA,18),ncol=3)

me_tab1[1:2,1] <- get_coef1(mnlint14_main,.1,0)
me_tab1[3:4,1] <- get_coef1(mnlint14_main,.1,.5)
me_tab1[5:6,1] <- get_coef1(mnlint14_main,.1,1)

me_tab1[1:2,2] <- get_coef1(mnlint28_main,.1,0)
me_tab1[3:4,2] <- get_coef1(mnlint28_main,.1,.5)
me_tab1[5:6,2] <- get_coef1(mnlint28_main,.1,1)

me_tab1[1:2,3] <- get_coef1(mnlint56_main,.1,0)
me_tab1[3:4,3] <- get_coef1(mnlint56_main,.1,.5)
me_tab1[5:6,3] <- get_coef1(mnlint56_main,.1,1)

# Table 4 -- The Effects of Ads on Pereived Probability of Winning the Primary

pro <- grp_4wk_p / 1000
runanti <- (grp_4wk_pa + grp_4wk_pc) / 1000
anti <- (grp_4wk_aa + grp_4wk_ac) / 1000
f2 <- prob ~ prob_cont + partymatch + pro + runanti + anti | respid + candid | 0 | respid

# all
proball_14 <- fix.felm(felm(f2,subset=primdist>14))
proball_28 <- fix.felm(felm(f2,subset=primdist>28))
proball_56 <- fix.felm(felm(f2,subset=primdist>56))
oProb1 <- output.models(list("2 weeks out"=proball_14,"4 weeks out"=proball_28,"8 weeks out"=proball_56))
oProb1 <- relabel.output(oProb1,oldivs=c("pro","runanti","anti","partymatch","prob_cont"),newivs=c("Promote","Attack","Get Attacked","Party Match","Baseline Prob."))
oProb1 <- relabel.output(oProb1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oProb1)

# less than .4
prob4_14 <- fix.felm(felm(f2,subset=primdist>14&prob_cont<.4))
prob4_28 <- fix.felm(felm(f2,subset=primdist>28&prob_cont<.4))
prob4_56 <- fix.felm(felm(f2,subset=primdist>56&prob_cont<.4))
oProb2 <- output.models(list("2 weeks out"=prob4_14,"4 weeks out"=prob4_28,"8 weeks out"=prob4_56))
oProb2 <- relabel.output(oProb2,oldivs=c("pro","runanti","anti","partymatch","prob_cont"),newivs=c("Promote","Attack","Get Attacked","Party Match","Baseline Prob."))
oProb2 <- relabel.output(oProb2,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oProb2)

# less than .2
prob2_14 <- fix.felm(felm(f2,subset=primdist>14&prob_cont<.2))
prob2_28 <- fix.felm(felm(f2,subset=primdist>28&prob_cont<.2))
prob2_56 <- fix.felm(felm(f2,subset=primdist>56&prob_cont<.2))
oProb3 <- output.models(list("2 weeks out"=prob2_14,"4 weeks out"=prob2_28,"8 weeks out"=prob2_56))
oProb3 <- relabel.output(oProb3,oldivs=c("pro","runanti","anti","partymatch","prob_cont"),newivs=c("Promote","Attack","Get Attacked","Party Match","Baseline Prob."))
oProb3 <- relabel.output(oProb3,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oProb3)

oProb <- combine.output(list(oProb1,oProb2,oProb3))
print.output(oProb,kstat=0)

# Tables A.1-A.12

effect1 <- function(Theta,Delta,Names,i,j,grps)
{
	temp <- Delta
	if(i == j) {
		temp[i] <- temp[i] + Theta[1] * grps
	} else {
		temp[i] <- temp[i] + Theta[2] * grps
		temp[j] <- temp[j] + Theta[3] * grps
	}
	(exp(temp) / sum0(exp(temp)) - exp(Delta) / sum0(exp(Delta)))[i]
}

effect2 <- function(Theta,Delta,Names,i,j,grps)
{
	temp <- Delta
	if(i == j) {
		temp[i] <- temp[i] + Theta[1] * grps
	} else {
		temp[i] <- temp[i] + Theta[2] * grps
		temp[j] <- temp[j] + Theta[3] * grps
	}
	(exp(temp) / sum0(exp(temp)) - exp(Delta) / sum0(exp(Delta)))[j]
}

prims <- c("2000 Democratic Primary","2000 Republican Primary","2004 Democratic Primary","2008 Democratic Primary","2008 Republican Primary","2012 Republican Primary")
Names <- matrix(rep(NA,6*9),nrow=6)
Names[1,1:2] <- c("Gore","Bradley")
Names[2,1:5] <- c("Bush","McCain","Forbes","Keyes","Bauer")
Names[3,] <- c("Kerry","Edwards","Clark","Dean","Gepardt","Lieberman","Kucinich","Mosely-Braun","Sharpton")
Names[4,1:6] <- c("Obama","Clinton","Edwards","Gravel","Kucinich","Richardson")
Names[5,1:8] <- c("McCain","Romney","Giuliani","Huckabee","Huntsman","Thompson","Ron Paul","Keyes")
Names[6,1:8] <- c("Romney","Gingrich","Paul","Perry","Huntsman","Santorum","Bachman","Cain")

mnlint28 <- mnlint28_main

base <- list()
me1 <- list()
me2 <- list()

for(k in 1:6)
{
	p <- sum(!is.na(mnlint28$Delta[k,]))

	mat1 <- matrix(rep(NA,9^2),nrow=9)
	for(i in 1:p) for(j in 1:p) mat1[j,i] <- effect1(mnlint28$theta,mnlint28$Delta[k,],Names[k,],i,j,1)
	rownames(mat1) <- Names[k,]
	colnames(mat1) <- Names[k,]
	base[[k]] <- (exp(mnlint28$Delta[k,]) / sum0(exp(mnlint28$Delta[k,])))
	names(base[[k]]) <- Names[k,]
	base[[k]] <- base[[k]][1:p]
	base[[k]] <- paste(dig2(100*base[[k]]),"\\%",sep="")
	me1[[k]] <- dig2(100*mat1[1:p,1:p])
	for(i in 1:p) for(j in 1:p) me1[[k]][j,i] <- paste(me1[[k]][j,i],"\\%",sep="")

	mat2 <- matrix(rep(NA,9^2),nrow=9)
	for(i in 1:p) for(j in 1:p) mat2[j,i] <- effect2(mnlint28$theta,mnlint28$Delta[k,],Names[k,],i,j,1)
	rownames(mat2) <- Names[k,]
	colnames(mat2) <- Names[k,]
	me2[[k]] <- dig2(100*mat2[1:p,1:p])
	for(i in 1:p) for(j in 1:p) me2[[k]][j,i] <- paste(me2[[k]][j,i],"\\%",sep="")
}

# Table A.13

sampfav <- !is.na(therm) & !is.na(partymatch) & !is.na(pro) & !is.na(runanti) & !is.na(anti) & (candparty=="D"|candparty=="R")
sampint <- !is.na(primint) & !is.na(partymatch) & !is.na(pro) & !is.na(runanti) & !is.na(anti) & (candparty=="D"|candparty=="R")

respsawads <- sum0(pro+runanti+anti,by=respid)>0
sawads <- respsawads[fmatch(respid,names(respsawads))]

samptab <- matrix(rep(NA,6*8),nrow=8)

samptab[1,1] <- sum0(sampfav)
samptab[2,1] <- sum0(sampfav&primdist>28)
samptab[3,1] <- sum0(sampfav&primdist>=0&primdist<=28)

samptab[1,2] <- dig1(100 * mean0(sawads,subset=sampfav))
samptab[2,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>14))
samptab[3,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>=0&primdist<=14))

samptab[1,3] <- length(unique(respid[sampfav]))
samptab[2,3] <- length(unique(respid[sampfav&primdist>14]))
samptab[3,3] <- length(unique(respid[sampfav&primdist>=0&primdist<=14]))

samptab[1,4] <- dig1(100 * length(unique(respid[sampfav&sawads])) / length(unique(respid[sampfav])))
samptab[2,4] <- dig1(100 * length(unique(respid[sampfav&primdist>14&sawads])) / length(unique(respid[sampfav&primdist>14])))
samptab[3,4] <- dig1(100 * length(unique(respid[sampfav&primdist>=0&primdist<=14&sawads])) / length(unique(respid[sampfav&primdist>=0&primdist<=14])))

samptab[1,5] <- length(unique(respid[sampint]))
samptab[2,5] <- length(unique(respid[sampint&primdist>14]))
samptab[3,5] <- length(unique(respid[sampint&primdist>=0&primdist<=14]))

samptab[1,6] <- dig1(100 * length(unique(respid[sampint&sawads])) / length(unique(respid[sampint])))
samptab[2,6] <- dig1(100 * length(unique(respid[sampint&primdist>14&sawads])) / length(unique(respid[sampint&primdist>14])))
samptab[3,6] <- dig1(100 * length(unique(respid[sampint&primdist>=0&primdist<=14&sawads])) / length(unique(respid[sampint&primdist>=0&primdist<=14])))

samptab[4,1] <- sum0(sampfav&primdist>28)
samptab[5,1] <- sum0(sampfav&primdist>=0&primdist<=28)

samptab[4,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>28))
samptab[5,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>=0&primdist<=28))

samptab[4,3] <- length(unique(respid[sampfav&primdist>28]))
samptab[5,3] <- length(unique(respid[sampfav&primdist>=0&primdist<=28]))

samptab[4,4] <- dig1(100 * length(unique(respid[sampfav&primdist>28&sawads])) / length(unique(respid[sampfav&primdist>28])))
samptab[5,4] <- dig1(100 * length(unique(respid[sampfav&primdist>=0&primdist<=28&sawads])) / length(unique(respid[sampfav&primdist>=0&primdist<=28])))

samptab[4,5] <- length(unique(respid[sampint&primdist>28]))
samptab[5,5] <- length(unique(respid[sampint&primdist>=0&primdist<=28]))

samptab[4,6] <- dig1(100 * length(unique(respid[sampint&primdist>28&sawads])) / length(unique(respid[sampint&primdist>28])))
samptab[5,6] <- dig1(100 * length(unique(respid[sampint&primdist>=0&primdist<=28&sawads])) / length(unique(respid[sampint&primdist>=0&primdist<=28])))

samptab[6,1] <- sum0(sampfav&primdist>56)
samptab[7,1] <- sum0(sampfav&primdist>=0&primdist<=56)
samptab[8,1] <- sum0(sampfav&primdist<0)

samptab[6,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>56))
samptab[7,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist>=0&primdist<=56))
samptab[8,2] <- dig1(100 * mean0(sawads,subset=sampfav&primdist<0))

samptab[6,3] <- length(unique(respid[sampfav&primdist>56]))
samptab[7,3] <- length(unique(respid[sampfav&primdist>=0&primdist<=56]))
samptab[8,3] <- length(unique(respid[sampfav&primdist<0]))

samptab[6,4] <- dig1(100 * length(unique(respid[sampfav&primdist>56&sawads])) / length(unique(respid[sampfav&primdist>56])))
samptab[7,4] <- dig1(100 * length(unique(respid[sampfav&primdist>=0&primdist<=56&sawads])) / length(unique(respid[sampfav&primdist>=0&primdist<=56])))
samptab[8,4] <- dig1(100 * length(unique(respid[sampfav&primdist<0&sawads])) / length(unique(respid[sampfav&primdist<0])))

samptab[6,5] <- length(unique(respid[sampint&primdist>56]))
samptab[7,5] <- length(unique(respid[sampint&primdist>=0&primdist<=56]))
samptab[8,5] <- length(unique(respid[sampint&primdist<0]))

samptab[6,6] <- dig1(100 * length(unique(respid[sampint&primdist>56&sawads])) / length(unique(respid[sampint&primdist>56])))
samptab[7,6] <- dig1(100 * length(unique(respid[sampint&primdist>=0&primdist<=56&sawads])) / length(unique(respid[sampint&primdist>=0&primdist<=56])))
samptab[8,6] <- dig1(100 * length(unique(respid[sampint&primdist<0&sawads])) / length(unique(respid[sampint&primdist<0])))

rownames(samptab) <- c("Full Sample","No Eminent Election","Eminent Election","No Eminent Election","Eminent Election","No Eminent Election","Eminent Election","After Election")
colnames(samptab) <- c("N","Per. Saw Ads","N","Per. Saw Ads","N","Per. Saw Ads")

samptab

# Table A.14

#######################
# ad numbers analysis #
#######################

pro <- num_4wk_p / 1000
runanti <- (num_4wk_pa + num_4wk_pc) / 1000
anti <- (num_4wk_aa + num_4wk_ac) / 1000

# favorability models
lm1_14 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oNum1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oNum1 <- relabel.output(oNum1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oNum1 <- relabel.output(oNum1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oNum1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oNum3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oNum3 <- relabel.output(oNum3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oNum3)

oNum <- combine.output(list(oNum1,oNum3))
print.output(oNum)

# save models for later
lm14_num <- lm1_14
lm28_num <- lm1_28
lm56_num <- lm1_56
mnlint14_num <- mnlint14
mnlint28_num <- mnlint28
mnlint56_num <- mnlint56

exp(mnlint14_num$coef[1]) / (1 + exp(mnlint14_num$coef[1])) - .5
exp(mnlint28_num$coef[1]) / (1 + exp(mnlint28_num$coef[1])) - .5
exp(mnlint56_num$coef[1]) / (1 + exp(mnlint56_num$coef[1])) - .5

mean0(1000*pro,subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>=0&primdist<28)

# Table A.15 -- Candidate-Month Fixed Effects

pro <- grp_4wk_p / 1000
runanti <- (grp_4wk_pa + grp_4wk_pc) / 1000
anti <- (grp_4wk_aa + grp_4wk_ac) / 1000
f3 <- therm ~ partymatch + pro + runanti + anti | respid + paste(candid,month(date),sep="_") | 0 | respid

# favorability models
lm1_14 <- fix.felm(felm(f3,subset=(candparty=="D"|candparty=="R")&primdist>14))
lm1_28 <- fix.felm(felm(f3,subset=(candparty=="D"|candparty=="R")&primdist>28))
lm1_56 <- fix.felm(felm(f3,subset=(candparty=="D"|candparty=="R")&primdist>56))
oMonth1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oMonth1 <- relabel.output(oMonth1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oMonth1 <- relabel.output(oMonth1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oMonth1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(month(date),year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(month(date),year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(month(date),year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oMonth3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oMonth3 <- relabel.output(oMonth3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oMonth3,kstat=0)

oMonth <- combine.output(list(oMonth1,oMonth3))
print.output(oMonth,kstat=0)

# save models for later
mnlint14_month <- mnlint14
mnlint28_month <- mnlint28
mnlint56_month <- mnlint56

# Table A.16 -- log specification

pro <- log(1 + grp_4wk_p / 1000)
runanti <- log(1 + (grp_4wk_pa + grp_4wk_pc) / 1000)
anti <- log(1 + (grp_4wk_aa + grp_4wk_ac) / 1000)

# favorability models
lm1_14 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oLog1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oLog1 <- relabel.output(oLog1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oLog1 <- relabel.output(oLog1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oLog1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oLog3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oLog3 <- relabel.output(oLog3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oLog3)

oLog <- combine.output(list(oLog1,oLog3))
print.output(oLog)

# save models for later
mnlint14_log <- mnlint14
mnlint28_log <- mnlint28
mnlint56_log <- mnlint56

# Table A.17 -- no IA, NH, or SC

pro <- grp_4wk_p / 1000
runanti <- (grp_4wk_pa + grp_4wk_pc) / 1000
anti <- (grp_4wk_aa + grp_4wk_ac) / 1000

# favorability models
lm1_14 <- fix.felm(felm(therm ~ partymatch + pro + runanti + anti | respid + candid | 0  | respid,subset=(candparty=="D"|candparty=="R")&primdist>14&state!="IA"&state!="NH"&state!="SC"))
lm1_28 <- fix.felm(felm(therm ~ partymatch + pro + runanti + anti | respid + candid | 0  | respid,subset=(candparty=="D"|candparty=="R")&primdist>28&state!="IA"&state!="NH"&state!="SC"))
lm1_56 <- fix.felm(felm(therm ~ partymatch + pro + runanti + anti | respid + candid | 0  | respid,subset=(candparty=="D"|candparty=="R")&primdist>56&state!="IA"&state!="NH"&state!="SC"))
oLate1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oLate1 <- relabel.output(oLate1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oLate1 <- relabel.output(oLate1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oLate1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14&state!="IA"&state!="NH"&state!="SC"))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28&state!="IA"&state!="NH"&state!="SC"))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56&state!="IA"&state!="NH"&state!="SC"))
oLate3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oLate3 <- relabel.output(oLate3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oLate3)

oLate <- combine.output(list(oLate1,oLate3))
print.output(oLate)

# save models for later
mnlint14_late <- mnlint14
mnlint28_late <- mnlint28
mnlint56_late <- mnlint56

# Table A.18 -- based on 2 weeks of ads

pro <- grp_2wk_p / 1000
runanti <- (grp_2wk_pa + grp_2wk_pc) / 1000
anti <- (grp_2wk_aa + grp_2wk_ac) / 1000

# favorability models
lm1_14 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oW1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oW1 <- relabel.output(oW1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oW1 <- relabel.output(oW1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oMain1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oW3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oW3 <- relabel.output(oW3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oW3)

oW <- combine.output(list(oW1,oW3))
print.output(oW)

# save models for later
mnlint14_W <- mnlint14
mnlint28_W <- mnlint28
mnlint56_W <- mnlint56

# table A.18 -- 8 weeks of ads

pro <- grp_8wk_p / 1000
runanti <- (grp_8wk_pa + grp_8wk_pc) / 1000
anti <- (grp_8wk_aa + grp_8wk_ac) / 1000

# favorability models
lm1_14 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(f1,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oWW1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oWW1 <- relabel.output(oWW1,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oWW1 <- relabel.output(oWW1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oWW1)

# candidate choice models
X <- cbind(pro,runanti,anti)
colnames(X) <- c("Promote","Attack","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oWW3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=stats1,statse=T)
oWW3 <- relabel.output(oWW3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oWW3)

oWW <- combine.output(list(oWW1,oWW3))
print.output(oWW)

# save models for later
mnlint14_WW <- mnlint14
mnlint28_WW <- mnlint28
mnlint56_WW <- mnlint56

# Table A.20 -- Robustness summary relative eff.

negrattab <- matrix(rep(NA,14*9),ncol=9)
rownames(negrattab) <- alternate(c("Baseline","Number of Ads","Cand.-Month FEs","Log","No IA, NH, or SC","IVs Based on 2 Weeks of Ads","IVs Based on 8 Weeks of Ads"),rep("",7))

negrattab[1:2,1] <- get_coef1(mnlint14_main,.1,0)
negrattab[3:4,1] <- get_coef1(mnlint14_num,.1,0)
negrattab[5:6,1] <- get_coef1(mnlint14_month,.1,0)
negrattab[7:8,1] <- get_coef1(mnlint14_log,.1,0)
negrattab[9:10,1] <- get_coef1(mnlint14_late,.1,0)
negrattab[11:12,1] <- get_coef1(mnlint14_W,.1,0)
negrattab[13:14,1] <- get_coef1(mnlint14_WW,.1,0)

negrattab[1:2,2] <- get_coef1(mnlint14_main,.1,.5)
negrattab[3:4,2] <- get_coef1(mnlint14_num,.1,.5)
negrattab[5:6,2] <- get_coef1(mnlint14_month,.1,.5)
negrattab[7:8,2] <- get_coef1(mnlint14_log,.1,.5)
negrattab[9:10,2] <- get_coef1(mnlint14_late,.1,.5)
negrattab[11:12,2] <- get_coef1(mnlint14_W,.1,.5)
negrattab[13:14,2] <- get_coef1(mnlint14_WW,.1,.5)

negrattab[1:2,3] <- get_coef1(mnlint14_main,.1,1)
negrattab[3:4,3] <- get_coef1(mnlint14_num,.1,1)
negrattab[5:6,3] <- get_coef1(mnlint14_month,.1,1)
negrattab[7:8,3] <- get_coef1(mnlint14_log,.1,1)
negrattab[9:10,3] <- get_coef1(mnlint14_late,.1,1)
negrattab[11:12,3] <- get_coef1(mnlint14_W,.1,1)
negrattab[13:14,3] <- get_coef1(mnlint14_WW,.1,1)

negrattab[1:2,4] <- get_coef1(mnlint28_main,.1,0)
negrattab[3:4,4] <- get_coef1(mnlint28_num,.1,0)
negrattab[5:6,4] <- get_coef1(mnlint28_month,.1,0)
negrattab[7:8,4] <- get_coef1(mnlint28_log,.1,0)
negrattab[9:10,4] <- get_coef1(mnlint28_late,.1,0)
negrattab[11:12,4] <- get_coef1(mnlint28_W,.1,0)
negrattab[13:14,4] <- get_coef1(mnlint28_WW,.1,0)

negrattab[1:2,5] <- get_coef1(mnlint28_main,.1,.5)
negrattab[3:4,5] <- get_coef1(mnlint28_num,.1,.5)
negrattab[5:6,5] <- get_coef1(mnlint28_month,.1,.5)
negrattab[7:8,5] <- get_coef1(mnlint28_log,.1,.5)
negrattab[9:10,5] <- get_coef1(mnlint28_late,.1,.5)
negrattab[11:12,5] <- get_coef1(mnlint28_W,.1,.5)
negrattab[13:14,5] <- get_coef1(mnlint28_WW,.1,.5)

negrattab[1:2,6] <- get_coef1(mnlint28_main,.1,1)
negrattab[3:4,6] <- get_coef1(mnlint28_num,.1,1)
negrattab[5:6,6] <- get_coef1(mnlint28_month,.1,1)
negrattab[7:8,6] <- get_coef1(mnlint28_log,.1,1)
negrattab[9:10,6] <- get_coef1(mnlint28_late,.1,1)
negrattab[11:12,6] <- get_coef1(mnlint28_W,.1,1)
negrattab[13:14,6] <- get_coef1(mnlint28_WW,.1,1)

negrattab[1:2,7] <- get_coef1(mnlint56_main,.1,0)
negrattab[3:4,7] <- get_coef1(mnlint56_num,.1,0)
negrattab[5:6,7] <- get_coef1(mnlint56_month,.1,0)
negrattab[7:8,7] <- get_coef1(mnlint56_log,.1,0)
negrattab[9:10,7] <- get_coef1(mnlint56_late,.1,0)
negrattab[11:12,7] <- get_coef1(mnlint56_W,.1,0)
negrattab[13:14,7] <- get_coef1(mnlint56_WW,.1,0)

negrattab[1:2,8] <- get_coef1(mnlint56_main,.1,.5)
negrattab[3:4,8] <- get_coef1(mnlint56_num,.1,.5)
negrattab[5:6,8] <- get_coef1(mnlint56_month,.1,.5)
negrattab[7:8,8] <- get_coef1(mnlint56_log,.1,.5)
negrattab[9:10,8] <- get_coef1(mnlint56_late,.1,.5)
negrattab[11:12,8] <- get_coef1(mnlint56_W,.1,.5)
negrattab[13:14,8] <- get_coef1(mnlint56_WW,.1,.5)

negrattab[1:2,9] <- get_coef1(mnlint56_main,.1,1)
negrattab[3:4,9] <- get_coef1(mnlint56_num,.1,1)
negrattab[5:6,9] <- get_coef1(mnlint56_month,.1,1)
negrattab[7:8,9] <- get_coef1(mnlint56_log,.1,1)
negrattab[9:10,9] <- get_coef1(mnlint56_late,.1,1)
negrattab[11:12,9] <- get_coef1(mnlint56_W,.1,1)
negrattab[13:14,9] <- get_coef1(mnlint56_WW,.1,1)

# Table A.21 -- robustness of crossover point
crossrobusttab <- matrix(rep(NA,14*3),ncol=3)
rownames(crossrobusttab) <- alternate(c("Baseline","Number of Ads","Cand.-Month FEs","Log","No IA, NH, or SC","IVs Based on 2 Weeks of Ads","IVs Based on 8 Weeks of Ads"),rep("",7))

crossrobusttab[1:2,1] <- get_coef2(mnlint14_main,.05)
crossrobusttab[3:4,1] <- get_coef2(mnlint14_num,.05)
crossrobusttab[5:6,1] <- get_coef2(mnlint14_month,.05)
crossrobusttab[7:8,1] <- get_coef2(mnlint14_log,.05)
crossrobusttab[9:10,1] <- get_coef2(mnlint14_late,.05)
crossrobusttab[11:12,1] <- get_coef2(mnlint14_W,.05)
crossrobusttab[13:14,1] <- get_coef2(mnlint14_WW,.05)

crossrobusttab[1:2,2] <- get_coef2(mnlint28_main,.05)
crossrobusttab[3:4,2] <- get_coef2(mnlint28_num,.05)
crossrobusttab[5:6,2] <- get_coef2(mnlint28_month,.05)
crossrobusttab[7:8,2] <- get_coef2(mnlint28_log,.05)
crossrobusttab[9:10,2] <- get_coef2(mnlint28_late,.05)
crossrobusttab[11:12,2] <- get_coef2(mnlint28_W,.05)
crossrobusttab[13:14,2] <- get_coef2(mnlint28_WW,.05)

crossrobusttab[1:2,3] <- get_coef2(mnlint56_main,.05)
crossrobusttab[3:4,3] <- get_coef2(mnlint56_num,.05)
crossrobusttab[5:6,3] <- get_coef2(mnlint56_month,.05)
crossrobusttab[7:8,3] <- get_coef2(mnlint56_log,.05)
crossrobusttab[9:10,3] <- get_coef2(mnlint56_late,.05)
crossrobusttab[11:12,3] <- get_coef2(mnlint56_W,.05)
crossrobusttab[13:14,3] <- get_coef2(mnlint56_WW,.05)

# Table A.22 -- Effect of Ads of Favorability, Binary Measure

pro <- grp_4wk_p / 1000
runanti <- (grp_4wk_pa + grp_4wk_pc) / 1000
anti <- (grp_4wk_aa + grp_4wk_ac) / 1000
fBin <- bin ~ partymatch + pro + runanti + anti | respid + candid | 0 | respid

lm1_14 <- fix.felm(felm(fBin,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm(felm(fBin,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm(felm(fBin,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oBin <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=c("N","C","r.squared"))
oBin <- relabel.output(oBin,oldivs=c("pro","runanti","anti","partymatch"),newivs=c("Promote","Attack","Get Attacked","Party Match"))
oBin <- relabel.output(oBin,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oBin)

# Table A.23 -- Contrast Ads Seperately

pro <- grp_4wk_p / 1000
runcon <- grp_4wk_pc / 1000
runanti <- grp_4wk_pa / 1000
anti <- grp_4wk_aa / 1000
con <- grp_4wk_ac / 1000
fContr <- therm ~ partymatch + pro + runcon + runanti + con + anti | respid + candid | 0 | respid
statsContr1 <- c("N","C","P-Value for Test of Attack = Contrast","P-Value for Test of Get Attacked = Get Contrasted")
statsContr3 <- c("N","Con. Rel. Eff. at 0","Con. Rel. Eff. at 1/2","Con. Rel. Eff. at 1","Con. Crossover","Att. Rel. Eff. at 0","Att. Rel. Eff. at 1/2","Att. Rel. Eff. at 1","Att. Crossover","Con. - Att. Rel. Eff. at 0","Con. - Att. Rel. Eff. at 1/2","Con. - Att. Rel. Eff. at 1","Con. - Att. Crossover")

fix.felm2 <- function(lm1,r.squared=F)
{
	lm1$ivs <- rownames(lm1$coef)
	lm1$theta <- as.vector(lm1$coef)
	lm1$se <- as.vector(lm1$se)
	lm1$stats <- list()
	lm1$stats$N <- lm1$N
	lm1$stats$C <- as.integer(lm1$p)
	if(r.squared) {
		lm1$stats$r.squared <- summary(lm1)$r.squared
	}
	lm1$V <- lm1$vcv
	lm1$stats$"P-Value for Test of Attack = Contrast" = pval.as.pval(wald.test(function(x) x[3]-x[4],lm1$coef,lm1$V)$pval)
	lm1$stats$"P-Value for Test of Get Attacked = Get Contrasted" = pval.as.pval(wald.test(function(x) x[5]-x[6],lm1$coef,lm1$V)$pval)
	lm1
}

# favorability models
lm1_14 <- fix.felm2(felm(fContr,subset=(candparty=="D"|candparty=="R")&primdist>14),r.squared=T)
lm1_28 <- fix.felm2(felm(fContr,subset=(candparty=="D"|candparty=="R")&primdist>28),r.squared=T)
lm1_56 <- fix.felm2(felm(fContr,subset=(candparty=="D"|candparty=="R")&primdist>56),r.squared=T)
oContr1 <- output.models(list("2 weeks out"=lm1_14,"4 weeks out"=lm1_28,"8 weeks out"=lm1_56),stats=statsContr1)
oContr1 <- relabel.output(oContr1,oldivs=c("pro","runcon","runanti","con","anti","partymatch"),newivs=c("Promote","Contrast","Attack","Get Contrasted","Get Attacked","Party Match"))
oContr1 <- relabel.output(oContr1,oldstats=c("N","C"),newstats=c("Observations","Respondents"))
print.output(oContr1)

# candidate choice models
X <- cbind(pro,runcon,runanti,con,anti)
colnames(X) <- c("Promote","Contrast","Attack","Get Contrasted","Get Attacked")
mnlint14 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>14))
mnlint28 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>28))
mnlint56 <- fix.mnl(mnl(primint,X,respid,primintchoice,paste(year,source,candparty,sep="_"),Opt="felogit",subset=(candparty=="D"|candparty=="R")&!is.na(primint)&primdist>56))
oContr3 <- output.models(list("2 weeks out"=mnlint14,"4 weeks out"=mnlint28,"8 weeks out"=mnlint56),stats=statsContr3,statse=T)
oContr3 <- relabel.output(oContr3,oldstats=c("N"),newstats=c("Respondents"))
print.output(oContr3)

oContr <- combine.output(list(oContr1,oContr3))
print.output(oContr)

## create the actual tables ##

file1 <- paste(dir1,"tables.tex",sep="")
latex_doc_start(file1)

# Table 1
latex_table_start(file1,5)
latex_add_line(file1,"\\\\")
latex_table_entry(file1,"",c("2000","2004","2008","2012","2016"))
latex_add_line(file1,"\\\\")
latex_add_line(file1,"\\textbf{General Election:} \\\\")
latex_table_entries(file1,c("\\hspace{.4cm}Positive GRPs","\\hspace{.4cm}Negative GRPs"),posnegtab[1:2,])
latex_add_line(file1,"\\\\ \\textbf{Primary Election:} \\\\")
latex_table_entries(file1,c("\\hspace{.4cm}Positive GRPs","\\hspace{.4cm}Negative GRPs"),posnegtab[3:4,])
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="Positive and Negative Advertising by Year. Numbers reported are measured in 1000s of GRPs.",label="PosNegTable")

# Table 2
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oMain,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTable")


# Table 3
latex_table_start(file1,3)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:3,")",sep="",collapse=""))
latex_add_line(file1,"\\\\")
latex_add_line(file1," & 2 weeks out & 4 weeks out & 8 weeks out \\\\ \\\\")
latex_add_line(file1,"\\textbf{Relative Vote Share} \\\\")
latex_add_line(file1,"\\textbf{of Attacked Candidate} \\\\ \\\\")
latex_table_entries(file1,c(0,"",.5,"",1,""),me_tab1)
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="Relative Effectiveness of Positive Advertising. Standard errors are in parentheses. $\\dagger$ indicates that the coefficient is statistically distinguishable from 1 at the 10\\% level.",label="METable")

# Table 4
latex_add_line(file1,"\\begin{landscape}")
latex_table_start(file1,9)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:9,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{Sample:} & \\multicolumn{3}{c}{All} & \\multicolumn{3}{c}{$Pr(Win) <= 0.4$} & \\multicolumn{3}{c}{$Pr(Win) <= 0.2$} \\\\")
latex_model(file1,c("Probability (baseline)","Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oProb)
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Perceived Probability of Winning the Primary. Analyses include respondent and candidate fixed effects. Standard errors clustered by respondent are in parentheses. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ProbTable")
latex_add_line(file1,"\\end{landscape}")

# Tables A.1-A.6

for(k in 1:6)
{
	p <- sum(!is.na(mnlint28_main$Delta[k,]))

	if(k == 3  | k >= 5) latex_add_line(file1,"\\begin{landscape}")
	latex_table_start(file1,p)
	latex_add_line(file1,"\\\\")
	latex_table_entry(file1,"",paste("\\textbf{",colnames(me1[[k]]),"}",sep=""))
	latex_add_line(file1,"\\\\")
	latex_table_entry(file1,"\\textbf{Baseline}",base[[k]])
	latex_add_line(file1,"\\\\")
	latex_table_entry(file1,"\\textbf{Positive Ads} (+1000 GRPs)",diag(me1[[k]]))
	latex_add_line(file1,"\\\\")
	latex_add_line(file1,"\\textbf{Negative Ads} (+1000 GRPs)\\\\")
	me1a <- me1[[k]]
	diag(me1a) <- NA
	latex_table_entries(file1,paste("\\hspace{.3cm}Attack",rownames(me1a)),me1a)
	latex_add_line(file1,"\\\\")
	latex_table_end(file1,caption=paste("Effect Sizes for Advertising (",prims[k],") -- Analyses report the change in predicted vote share from increasing positive or negative ad spending by 1000 GRPs, relative to a baseline of no ad spending by all candidates.",sep=""),label=paste("EffectTable",k,sep=""))
	if(k == 3  | k >= 5) latex_add_line(file1,"\\end{landscape}")
}

# Tables A.7-A.12

for(k in 1:6)
{
	p <- sum(!is.na(mnlint28_main$Delta[k,]))

	if(k == 3  | k >= 5) latex_add_line(file1,"\\begin{landscape}")
	latex_table_start(file1,p)
	latex_add_line(file1,"\\\\")
	latex_table_entry(file1,"",paste("\\textbf{",colnames(me2[[k]]),"}",sep=""))
	latex_add_line(file1,"\\\\")
	latex_table_entry(file1,"\\textbf{Baseline}",base[[k]])
	latex_add_line(file1,"\\\\")
	latex_add_line(file1,"\\textbf{Negative Ads} (+1000 GRPs)\\\\")
	me1a <- me1[[k]]
	diag(me1a) <- NA
	latex_table_entries(file1,paste("\\hspace{.3cm}Attack",rownames(me1a)),me1a)
	latex_add_line(file1,"\\\\")
	latex_table_end(file1,caption=paste("Effect Sizes for Advertising on Attacked Candidate (",prims[k],") -- Analyses report the change in predicted vote share from increasing negative ad spending by 1000 GRPs, relative to a baseline of no ad spending by all candidates.",sep=""),label=paste("EffectTable",k+6,sep=""))
	if(k == 3  | k >= 5) latex_add_line(file1,"\\end{landscape}")
}

# Table A.13
# sample description
latex_table_start(file1,6)
latex_add_line(file1,"\\\\ \\textbf{DV:} &\\multicolumn{4}{c}{\\textbf{Favorability}} & \\multicolumn{2}{c}{\\textbf{Vote Intention}} \\\\")
latex_add_line(file1,"\\\\")
latex_add_line(file1," & Observations & Per. w/   & Respondents & Per. w/   & Respondents & Per. w/   \\\\")
latex_add_line(file1," &      & Pos. Adv. &       & Pos. Adv. &       & Pos. Adv. \\\\")
latex_add_line(file1,"\\\\")
latex_table_entry(file1,rownames(samptab)[1],samptab[1,])
latex_add_line(file1,"\\\\")
latex_add_line(file1,"\\\\ 2 Week Window: \\\\")
latex_table_entries(file1,paste("\\hspace{.4cm}",rownames(samptab)[2:3],sep=""),samptab[2:3,])
latex_add_line(file1,"\\\\")
latex_add_line(file1,"\\\\ 4 Week Window: \\\\")
latex_table_entries(file1,paste("\\hspace{.4cm}",rownames(samptab)[4:5],sep=""),samptab[4:5,])
latex_add_line(file1,"\\\\")
latex_add_line(file1,"\\\\ 8 Week Window: \\\\")
latex_table_entries(file1,paste("\\hspace{.4cm}",rownames(samptab)[6:7],sep=""),samptab[6:7,])
latex_add_line(file1,"\\\\")
latex_table_entry(file1,rownames(samptab)[8],samptab[8,])
latex_add_line(file1,"\\\\")
latex_add_line(file1,"\\\\")
latex_table_end(file1,caption="Sample Summary",label="SampTable")


# Table A.14
## number of ads
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oNum,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Independent Variables Based on Number of Ads. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableNum")


# Table A.15
# candidate-month FEs
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oMonth,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Candidate-Month Fixed Effects. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableCM")


# Table A.16
# logs
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oLog,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Logged Ads. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableLog")


# Table A.17
# no IA, NH, or SC
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oLate,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, No IA, NH, or SC. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableNoEarly")


# Table A.18
# two weeks
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oW,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Independent Variables Based on Two Weeks of Ads. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableWk2")


# Table A.19

# eight weeks
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oWW,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Independent Variables Based on Eight Weeks of Ads. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableWk8")


# Table A.20
latex_add_line(file1,"\\begin{landscape}")
latex_table_start(file1,9)
latex_add_line(file1,"\\\\ & \\multicolumn{3}{c}{2 weeks out} & \\multicolumn{3}{c}{4 weeks out} & \\multicolumn{3}{c}{8 weeks out} \\\\")
latex_add_line(file1,"\\textbf{Relative vote share} & 0 & 0.5 & 1 & 0 & 0.5 & 1 & 0 & 0.5 & 1 \\\\")
latex_add_line(file1,"\\textbf{of Attacked Candidate} \\\\ \\\\")
latex_add_line(file1,"\\\\")
latex_table_entries(file1,rownames(negrattab),negrattab)
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="Robustness Checks for the Relative Effectiveness of Positive Advertising -- Each entry computes $\\frac{     \\theta_1}{\\theta_2 - \\tfrac{e^{u_2}}{e^{u_2} + C} \\theta_3}$ for a particular model, where $\\tfrac{e^{u_2}}{e^{u_2} + C}$ is the vote share of the attacked candidate relative to all candidates except the attacker. A dagger indicates that the coefficient is statistically significantly different than 1 at the 5\\% level.",label="NegRatRobTable")
latex_add_line(file1,"\\end{landscape}")

# Table A.21
latex_table_start(file1,3)
latex_add_line(file1,"\\\\ & 2 weeks out & 4 weeks out & 8 weeks out \\\\ \\\\")
latex_table_entries(file1,rownames(crossrobusttab),crossrobusttab)
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="Robustness Checks for the Crossover Point. Each entry computes $\\frac{\\theta_3}{\\theta_2}$ for a particular model, where attacked candidates loose vote share when $\\tfrac{1}{1+C} < \\frac{\\theta_3}{\\theta_2}$ and gain vote share otherwise. Here, $\\tfrac{1}{1+C}$ is the vote share of the attacking candidate relative to all candidates except the attacked candidate. One star indicates that the coefficient is statistically significantly different from 0 at the 5\\% level and one dagger indicates that the coefficient is statistically significantly different from 1 at the 5\\% level.",label="CrossRobTable")


# Table A.22
latex_table_start(file1,3)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:3,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Negative Ads","Attacked by Negative Ads"),oBin,stats=c("Observations","Respondents"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability, Binary Measure. Analyses include respondent and candidate fixed effects. Standard errors clustered by respondents are in parentheses. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ResultsTableBin")


# Table A.23

latex_add_line(file1,"\\begin{landscape}")
latex_table_start(file1,6)
latex_add_line(file1,"\\\\")
latex_add_line(file1,paste(" & (",1:6,")",sep="",collapse=""))
latex_add_line(file1,"\\\\ \\textbf{DV:} & \\multicolumn{3}{c}{Favorability} & \\multicolumn{3}{c}{Candidate Choice} \\\\")
latex_model(file1,c("Party Match","Run Positive Ads","Run Contrast Ads","Run Negative Ads","Attacked by Contrast Ads","Attacked by Negative Ads"),oContr,stats=c("Observations","Respondents","P-Value for Test of Attack = Contrast","P-Value for Test of Get Attacked = Get Contrasted","Con. - Att. Rel. Eff. at 0","Con. - Att. Rel. Eff. at 1/2","Con. - Att. Rel. Eff. at 1","Con. - Att. Crossover"))
latex_add_line(file1,"\\\\") 
latex_table_end(file1,caption="The Effects of Ads on Favorability and Candidate Choice, Contrast vs. Primarily Negative Ads. Analyses include respondent and candidate fixed effects (columns 1-3) and candidate fixed effects (columns 4-6). Standard errors are in parentheses and are clustered by respondent in columns 1-3. One star indicates statistical significance at the 5\\% level. Two stars indicates statistical significance at the 1\\% level. Three stars indicates statistical significance at the 0.1\\% level. A plus sign indicates statistical significance at the 10\\% level.",label="ContrastTable")
latex_add_line(file1,"\\end{landscape}")

latex_doc_end(file1)

#### END ####






